You use extern "C"
to prevent name mangling inside header files and your C++ object files for libraries or objects that have already been compiled without mangling.
For example, say you have a widget
library which was compiled with a C compiler so that its published interface is non-mangled.
If you include the header file as is into your code, it will assume the names are mangled and those mangled versions are what you'll tell the linker to look for.
However, since you'll be asking for something like function@intarray_float_charptr
and the widget
library will have only published function
, you're going to run into problems.
However, if you include it with:
extern "C" {
#include "widget.h"
}
your compiler will know that it should try to use function
, the non-mangled version.
That's why, in header files for C stuff meant to be included in C _or C++ programs, you'll see things like:
#ifdef __cplusplus
extern "C" {
#endif
// Everything here works for both C and C++ compilers.
#ifdef __cplusplus
}
#endif
If you use a C compiler to include this, the #ifdef
lines will cause the extern "C"
stuff to disappear. For a C++ compiler (where __cplusplus
is defined), everything will be non-mangled.
<string.h>
to avoid name mangling, use the<cstring>
header. – Hyman<cxxx>
. If you write C, use<xxx.h>
and compile your code with a C compiler. Mixing languages is not a good idea. – Hyman#include
inside anextern "C"
. Standard C library headers take care of checking if__cplusplus
is defined and addingextern "C"
for you. Where you might have to wrap in#include
insideextern "C"
would be a 3rd-party C library that didn't do the#ifdef __cplusplus
checking for you. – Rrhoeastd::
in front of every function you call from a<cxxx>
header? Can there still be portability problems? – Rrhoea