[ACCEPTED]-Undefined Reference to a function-undefined-reference

Accepted answer
Score: 17

If you're really compiling fileA.c as C, not C++, then 12 you need to make sure that the function 11 has the proper, C-compatible linkage.

You 10 can do this with a special case of the extern keyword. Both 9 at declaration and definition:

extern "C" void F1();
extern "C" void F1() {}

Otherwise 8 the C linker will be looking for a function 7 that only really exists with some mangled 6 C++ name, and an unsupported calling convention. :)

Unfortunately, whilst 5 this is what you have to do in C++, the syntax isn't valid in C. You 4 must make the extern visible only to the C++ code.

So, with 3 some preprocessor magic:

#ifdef __cplusplus
extern "C"
void F1();

Not entirely pretty, but 2 it's the price you pay for sharing a header 1 between code of two languages.

Score: 5

To be able to call a c++ function from c 3 source code you neeed to give the appropriate 2 linkage specification.

The format for specifying linkage specification 1 is

extern "type_of_Linkage" <function_name>

So in your case, you should be using:

extern "C" void F1();
Score: 4

perhaps, use

extern "C" void F1();


Score: 2

fileA.c can't include fileB.h (via fileA.h) because 5 the C compiler doesn't know what extern 4 "C" means, so it complains that it sees 3 an identifier before a string. don't try 2 to include fileB.h in fileA.c or fileA.h. its 1 not needed

Score: 0

fileA.c needs to also include fileA.h I 1 believe.

More Related questions