Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Effect of Declaring 'extern "C"' in the Header to a C++ Shared Library?

Based on this question I understand the purpose of the construct in linking C libraries with 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 number of function declarations. If the header includes the extern "C" declaration...

#ifdef __cplusplus
extern "C"
{
#endif

  // typedef struct ...;
  // function decls

#ifdef __cplusplus
}
#endif

... what is the effect? Specifically I'm wondering if there are any detrimental side effects of that declaration since the shared library is compiled as C++, not C.

Is there any reason to have the extern "C" declaration in this case?

like image 242
Adam Holmberg Avatar asked Apr 06 '10 19:04

Adam Holmberg


1 Answers

This is important so that the compiler doesn't name mangle. C++ uses name mangling to differentiate functions with operator overloads.

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

extern "C" prevents that name mangling.

IIRC, that makes it possible for program to dynamically link in symbols at run time. It's common for "plugin" type architectures.

like image 195
Stephen Avatar answered Sep 28 '22 02:09

Stephen