What is the effect of declaring "extern" C "'in the header for the C ++ shared library?

Based on this question , I understand the purpose of the construct in linking C libraries to C ++ code. Now suppose the following:

I have a '.so' shared library compiled with a C ++ compiler. The header has a "typedef stuct" and a series of function declarations. If the header contains the extern expression "C" ...

#ifdef __cplusplus extern "C" { #endif // typedef struct ...; // function decls #ifdef __cplusplus } #endif 

... what is the effect? In particular, I am wondering if there are any negative side effects of this declaration, since the shared library is compiled as C ++, not C.

Is there any reason for declaring extern "C" in this case?

+6
c ++ c linux shared-libraries extern
source share
5 answers

It is important that the compiler does not name mangle. C ++ uses name management to differentiate functions with operator overloads.

Run "/ usr / bin / nm" in binary format to see what C ++ does with your function names: _ZSt8_DestroyIN9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEEiEvT_S7_SaIT0_E

extern "C" prevents a name change.

IIRC, which allows the program to dynamically bind characters at runtime. It is common for plug-in architectures.

+11
source share

When compiling C ++, the method name changes (mangling) - and you cannot call this method from another dll / exe that uses C.

To save the name of the class and method, you need to compile them as "C" without changing the name.

The library is still a C ++ library, but it provides some of its declarations (those in the extern "c" block) as C methods.

+4
source share

A #ifdef #ifdef declaration must indicate by C-linkers that characters have C (unencrypted) character table entries. #ifdef ensures that there is no effect in the code module (file) compiled by the C compiler.

+3
source share

One of the advantages of using extern "C" for the C ++ API is that it prevents function overloading:

 extern "C" { // ILLEGAL - C linkage does not support function overloading void foo(int x); void foo(const char *str); } 
0
source share

#ifdef in this example means that only the C ++ compiler will see that extern wrapping the header file, which will mean that it will generate abnormal names. The C compiler does not see extern (which it does not understand), but always creates intact names.

This means that both C and C ++ compilers will produce the same characters in their object files, therefore, depending on which compiler creates the object code for the declared functions, all object files will be successfully linked because the characters have one the same connection and the same name.

There should be no consequences for static linking or linking to a shared library.

0
source share

All Articles