我在头文件和源文件中都有此代码。这是代码的小片段。这是来自.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()'
有人有什么想法吗?
请记住,C ++ mangles其函数名称。因此,在C ++中名为sample
的函数在C中将不会被命名为相同的函数。
当然,相反,C中的void RandomInitialise(int,int)
之类的函数不会在C ++中简单地命名为RandomInitialise
。
您必须对使用C实现的函数使用extern "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
右键单击此处,然后“添加文件”,然后选择要编辑其文件传递的.h和.c文件,然后按OK。
<<