C++ -- extern, extern "C" -- mangling
extern keyword can be used as
- a storage class specifier for a variable
- to tell the compiler how to link to an external function.
extern
The extern keyword is used to inform the compiler about variables declared outside of the current scope. Variables described by extern statements will not have any space allocated for them, as they should be properly defined elsewhere.
Extern statements are frequently used to allow data to span the scope of multiple files. An external variable must be defined, exactly once, outside of any function.
extern “C” and mangling
Since C++ has overloading of function names and C does not, the C++ compiler cannot just use the function name as a unique id to link to, so it mangles the name by adding information about the arguments. A C compiler does not need to mangle the name since you can not overload function names in C. When you state that a function has extern “C” linkage in C++, the C++ compiler does not add argument/parameter type information to the name used for linkage. For example {test.cpp}
foo function is decorated. Now with {test.cpp}
foo function is not decorated.
If you want to mix C and C++ code add the following guards in your C code.
This allows to have the good decoration when you link with the C/C++ libraries.
If you found this post or this website helpful and would like to support our work, please consider making a donation. Thank you!
Help Us