Linkage between C++ and non-C++ code fragments is called language linkage. All function types, function names, and variable names have a language linkage, which by default is C++.
Linkage specification syntax >>-extern--string_literal--+-declaration---------------+------->< | .-----------------. | | V | | '-{----+-------------+-+--}-' '-declaration-'
extern "C" { #include "shared.h" }
// in C++ program extern "C" int displayfoo(const char *); int main() { return displayfoo("hello"); } /* in C program */ #include <stdio.h> extern int displayfoo(const char * str) { while (*str) { putchar(*str); putchar(' '); ++str; } putchar('\n'); }
Name mangling is the encoding of function and variable names into unique names so that linkers can separate common names in the language. Type names may also be mangled. Name mangling is commonly used to facilitate the overloading feature and visibility within different scopes. The compiler generates function names with an encoding of the types of the function arguments when the module is compiled. If a variable is in a namespace, the name of the namespace is mangled into the variable name so that the same variable name can exist in more than one namespace. The C++ compiler also mangles C variable names to identify the namespace in which the C variable resides.
The scheme for producing a mangled name differs with the object model used to compile the source code: the mangled name of an object of a class compiled using one object model will be different from that of an object of the same class compiled using a different object model. The object model is controlled by compiler option or by pragma.
extern "C" { int f1(int); int f2(int); int f3(int); };This declaration tells the compiler that references to the functions f1, f2, and f3 should not be mangled.
extern "C" { void p(int){ /* not mangled */ } };
extern "C" { extern "C++" { void func(); } }In this example, func has C++ linkage.