1

我在头文件和源文件中有这段代码。这是代码的小片段。这是来自.cpp文件。

int sample(Cdf* cdf)  
{
    //double RandomUniform();
    double r = RandomUniform(); //code that is causing the error
    for (int j = 0; j < cdf->n; j++)
    if (r < cdf->vals[j])
    return cdf->ids[j];
    // return 0;
}

这是来自.c文件:

double RandomUniform(void)
{
    double uni;

    /* Make sure the initialisation routine has been called */
    if (!test) 
    RandomInitialise(1802,9373);

    uni = u[i97-1] - u[j97-1];
    if (uni <= 0.0)
    uni++;
    u[i97-1] = uni;
    i97--;

    // ...
}

这是来自我的头文件

void   RandomInitialise(int,int);
double RandomUniform();
double RandomGaussian(double,double);
int    RandomInt(int,int);
double RandomDouble(double,double);

#include "headerfile.h".cpp文件中使用过,然后我编译了代码。从片段中可以看出,我基本上RandomUniform()是在调用文件中的函数,.cpp然后在头文件中定义它。

问题是,每当我构建程序时,都会收到“未定义的函数引用”错误。这是我得到的错误

       In function 'Z6sampleP3Cdf':
       undefined reference to 'RandomUniform()'

有人知道吗?

4

3 回答 3

5

请记住,C++ 会破坏其函数名称。因此sample,在 C++ 中命名的函数在 C 中将不会被命名为相同的名称。

当然,相反,像void RandomInitialise(int,int)C 中的函数不会RandomInitialise在 C++ 中简单地命名。

您必须使用用extern "C"C 实现的函数,否则 C++ 编译器将为您的 C 函数创建错位名称。

因此,您必须将包含这些仅 C 函数的头文件更改为:

extern "C" void   RandomInitialise(int,int);
extern "C" double RandomUniform(void);
extern "C" double RandomGaussian(double,double);
extern "C" int    RandomInt(int,int);
extern "C" double RandomDouble(double,double);

当然,这意味着您不能使用纯 C 项目中的相同头文件,因为extern "C"在纯 C 编译器中无效。但是您可以使用预处理器来帮助解决这个问题:

#ifdef __cplusplus
extern "C" {
#endif

void   RandomInitialise(int,int);
double RandomUniform(void);
double RandomGaussian(double,double);
int    RandomInt(int,int);
double RandomDouble(double,double);

#ifdef __cplusplus
}
#endif
于 2013-03-16T22:20:57.877 回答
2

如果您没有在文件创建时将文件添加到调试发布!那么问题就来了!

cpp文件需要链接和添加!如果不在调试和|或发布中!链接器将找不到它们!

如何将它们添加到调试或发布

如果它们已经创建!在文件资源管理器左边!右键点击!并选择属性!在属性中选择build!您将找到添加调试和发布的位置!

在此处输入图像描述 在此处输入图像描述

关于外部“C”的注意事项

不需要添加外部“C”!我确认!链接器链接没有问题!

仍然检查这个答案

https://stackoverflow.com/a/15455385/7668448

https://stackoverflow.com/a/15141021/7668448

于 2020-06-28T09:47:12.270 回答
-4

右键单击此处,然后“添加文件”,然后选择要编辑其文件传递的 .h 和 .c 文件,然后按确定。

单击此处查看按的位置

于 2019-12-15T21:26:36.203 回答