我在头文件和源文件中有此代码。这是代码的小片段。这是来自.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;
}
Run Code Online (Sandbox Code Playgroud)
这是从.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--;
// ...
}
Run Code Online (Sandbox Code Playgroud)
这是从我的头文件
void RandomInitialise(int,int);
double RandomUniform();
double RandomGaussian(double,double);
int RandomInt(int,int);
double RandomDouble(double,double);
Run Code Online (Sandbox Code Playgroud)
我#include "headerfile.h"在.cpp文件中使用过,然后编译了代码。从片段中可以看到,我基本上RandomUniform()是在调用.cpp文件中的函数,然后在头文件中对其进行定义。
问题是,每当我构建程序时,都会出现“未定义的函数引用”错误。这是我得到的错误
In function 'Z6sampleP3Cdf':
undefined reference to 'RandomUniform()'
Run Code Online (Sandbox Code Playgroud)
有人知道吗
请记住,C ++会破坏其函数名称。因此sample,用C ++ 命名的函数在C中的命名将不同。
相反,在C ++中void RandomInitialise(int,int)不会像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);
Run Code Online (Sandbox Code Playgroud)
当然,这意味着您不能使用纯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
Run Code Online (Sandbox Code Playgroud)