C code compiled with C ++: undefined link

I have a small program that I can compile with GCC and ICC without any difficulty, but I would also like the code to work with g ++ and ICPC. I tried to add this:

#ifdef __cplusplus extern "C" { #endif 

at the beginning and further:

 #ifdef __cplusplus } #endif 

at the end of all header files, but I still get a few <undefined links to "..." errors.

+6
c ++ c undefined-reference include
source share
4 answers

I think you're wrong ... Extern C is for disabling the mangling function; therefore, if you do this only for header files, when you try to link your garbled object code, the declared function names will not match the function names in the object file.

In any case, extern C will not add any portability if the entire application is compiled and linked to the same C ++ compiler, which is designed to mix C libraries with C ++ code.

If your code is in a common subset of C and C ++, you can already compile it with any compiler, but I see no reason for this (besides working on the principle of least surprise, since C ++ is more strict with some things).

+7
source share

You get undefined links because the declaration and definition do not match if you put extern "C" , which prevents the name from getting distorted, but in this case it only happens in your header files.

+2
source share

If one of the undefined links is gxx_personality, then I would say that the message "fortran" is correct.

+1
source share

See my answer to this earlier question: When to use extern "C" in simple words?

It is hoped that it will be clear how to mix C and C ++ code.

+1
source share

All Articles