Hello, Stack Overflow!
I was wondering what exactly putting 'extern "C"' in your C++ program does.
Thanks!
Hello, Stack Overflow!
I was wondering what exactly putting 'extern "C"' in your C++ program does.
Thanks!
It informs the C++ compiler to look up the names of those functions in a C-style when linking, because the names of functions compiled in C and C++ are different during the linking stage.
It changes the linkage of a function in such a way that the function is callable from C. In practice that means that the function name is not mangled.
extern "C" makes a function-name in C++ have 'C' linkage (compiler does not mangle the name) so that client C code can link to (i.e use) your function using a 'C' compatible header file that contains just the declaration of your function. Your function definition is contained in a binary format (that was compiled by your C++ compiler) that the client 'C' linker will then link to using the 'C' name.
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.
Just so you know, you can specify "C" linkage to each individual declaration/definition explicitly or use a block to group a sequence of declarations/definitions to have a certain linkage:
extern "C" void foo(int);
extern "C"
{
void g(char);
int i;
}
If you care about the technicalities, they are listed in section 7.5 of the C++03 standard, here is a brief summary (with emphasis on extern "C"):
I'd like to introduce you this article:
http://www.agner.org/optimize/calling_conventions.pdf
It tells you much more about calling convention and the difference between different compiler.
In every C++ program, all non-static functions are represented in the binary file as symbols. These symbols are special text strings that uniquely identify a function in the program.
In C, the symbol name is the same as the function name. This is possible because in C no two non-static functions can have the same name.
Because C++ allows overloading and has many features that C does not — like classes, member functions, exception specifications - it is not possible to simply use the function name as the symbol name. To solve that, C++ uses so-called name mangling, which transforms the function name and all the necessary information (like the number and size of the arguments) into some weird-looking string which only the compiler knows about.
So if you specify a function to be extern C, the compiler doesn't performs name mangling with it and it can be directly accessed using its symbol name.
This comes handy while using dlsym()
and dlopen()
for calling such functions.