What
happens if you’re writing a program in C++ and you want to use a C
library? If you make the C function declaration,
float
f(int a, char b);
the
C++ compiler will mangle (decorate) this name to something like
_f_int_int
to support function overloading (and type-safe linkage). However, the C
compiler that compiled your C library has most definitely
not
mangled the name, so its internal name will be
_f.
Thus, the linker will not be able to resolve your C++ calls to
f( ).
The
escape mechanism provided in C++ is the
alternate
linkage specification
,
which was produced in the language by overloading the
externkeyword.
The
extern
is followed by a string that specifies the linkage you want for the
declaration, followed by the declaration itself:
extern
"C" float f(int a, char b);
This
tells the compiler to give C linkage to
f( );
that is, don’t mangle the name.
The only two types of linkage specifications supported by the standard are
“C”
and
“C++,”
but compiler vendors have the option of supporting other languages in the same
way.
If
you have a group of declarations with alternate linkage, put them inside
braces, like this:
extern "C" {
float f(int a, char b);
double d(int a, char b);
}
Or,
for a header file,
extern "C" {
#include "Myheader.h"
}
Most
C++ compiler vendors handle the alternate linkage specifications inside their
header files that work with both C and C++, so you don’t have to worry
about it.
The
only alternate linkage specification strings that are standard are
“C” and “C++” but implementations can support other
languages using the same mechanism.