user2035796 user2035796 - 1 year ago 203
C Question

Undefined reference to function in Codeblocks

I have this code here in a header file and source files. Here are little snippets of the code. This is from the


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;

This is from the

double RandomUniform(void)
double uni;

/* Make sure the initialisation routine has been called */
if (!test)

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

// ...

And this is from my header file

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

I have used
#include "headerfile.h"
in the
file and then I compiled the code. As you can see from the snippets, I am basically calling the function
that is in the
file then defining it in the header file.

Problem is, whenever I build the program, I get an "undefined reference to function" error.
Here is the error I am getting

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

Anybody have any idea?

Answer Source

Remember that C++ mangles its function names. So a function named sample in C++ will not be named the same in C.

And the oposite of course, a function like void RandomInitialise(int,int) in C will not be simply named RandomInitialise in C++.

You have to use extern "C" for your function implemented in C, or the C++ compiler will create mangled names for your C functions.

So you have to change your header file containing these C-only functions as:

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);

Of course this means you can't use the same header file from a pure C project, as extern "C" is not valid in a pure C compiler. But you can use the preprocessor to help with that:

#ifdef __cplusplus
extern "C" {

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

#ifdef __cplusplus
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download