Name Mangling and Extern C in C++ Concept
Name mangling is a technique used by C++ compilers to encode the names of functions and variables in a way that includes type information. This is primarily done to support function overloading and to allow C++ to link with C code. When C++ code is compiled, the names of functions and variables are transformed into a mangled form to include type information, which helps the compiler distinguish between overloaded functions.
For example, consider these two C++ functions:
int add(int a, int b);
float add(float a, float b);
In the object code generated by the C++ compiler, these functions may have mangled names like _Z3addii
and _Z3addff
. These mangled names include information about the function name, the number, and types of parameters, and sometimes other details.
Now, consider the use case where you have C++ code that you want to link with C code. C does not have name mangling because it does not support function overloading or type-based differentiation. Therefore, you need a way to inform the C++ compiler that the functions you are trying to link with have C linkage and should not be name-mangled. This is where the extern "C"
linkage specification comes into play.
When you declare a function or variable with extern "C"
, you are telling the C++ compiler to use C linkage for that particular item. This means that the compiler will not apply name mangling to it, making it compatible with C code.
Here’s an example:
// C++ code
extern "C" {
int add(int a, int b);
// ...
}
In this example, the add
function is declared with C linkage using extern "C"
. When this code is compiled, the add
function will not undergo name mangling, and its symbol will be compatible with C code.
This is commonly used when you have a C++ program that needs to interface with C libraries or when you are writing a C++ wrapper around a C library. The extern "C"
linkage specification ensures that the C++ code can call C functions without any name-mangling issues.