Undefined Function Link

I am using Linux and I have the following files:

main.c, main.h fileA.c, fileA.h fileB.cpp, fileB.h 

The F1() function is declared in fileB.h and is defined in fileB.cpp . I need to use a function in fileA.c , and so I declared this function as

 extern void F1(); 

in fileA.c .

However, during compilation I got an error

 fileA.c: (.text+0x2b7): undefined reference to `F1' 

What's wrong?

Thanks.

ETA: Thanks to the answers I now have the following:

In file.h I have

 #include fileB.h #include main.h #ifdef __cplusplus extern "C" #endif void F1(); 

In file.c file, I have

 #include fileA.h 

In fileB.h I have

 extern "C" void F1(); 

In fileB.cpp I have

 #include "fileB.h" extern "C" void F1() { } 

However now i have an error

 fileB.h: error: expected identifier or '(' before string constant 
+4
source share
5 answers

If you really compile fileA.c as C, not C ++, then you need to make sure that the function has the correct C-compatible reference.

You can do this with the extern keyword special case. And when declaring and defining:

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

Otherwise, the C-linker will look for a function that really exists only with some garbled C ++ name and an unsupported call. :)

Unfortunately, although this is what you need to do in C ++, the syntax is not valid in C. You should make extern visible only to C ++ code.

So, with some preprocessor magic:

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

Not entirely beautiful, but this is the price you pay for the header exchange between the code of the two languages.

+15
source

To be able to call a C ++ function from source, you must specify the appropriate linkage specification .

Binding Specification Job Format

 extern "type_of_Linkage" <function_name> 

So in your case you should use:

 extern "C" void F1(); 
+5
source

maybe use

 extern "C" void F1(); 
+4
source

fileA.c cannot include fileB.h (via fileA.h) because the C compiler does not know what extern "C" means, so it complains that it sees the identifier before the line. do not try to include fileB.h in file A.c or fileA.h. don't need him

+2
source

fileA.c should also include fileA.h, I believe.

-1
source

All Articles