I have to convert some C/C++ code to Java. My C++ is extremely rusty.
In a .h
file, I have the following:
#ifdef __cplusplus
extern "C" {
#endif
/* tons of declarations */
#ifdef __cplusplus
} /* extern C */
#endif
What is the use of extern "C"
? What does it mean? Is it telling the compiler that corresponding code should be interpreted as pure C, rather than C++?
EDIT
Thanks for the answers so far. The history of the code I have to convert is that it seems like a part was written in C first, then the rest was written in C++. So my header file seems to correspond to 'old' C code.
I'll convert this code into a public final class
with static method and attributes. No overriding.
The extern must be applied to all declarations in all files. (Global const variables have internal linkage by default.) extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block.
Not any C-header can be made compatible with C++ by merely wrapping in extern "C".
Using extern "C" lets the compiler know that we want to use C naming and calling conventions. This causes the compiler to sort of entering C mode inside our C++ code. This is needed because C++ compilers mangle the names in their symbol table differently than C compilers and hence behave differently than C compilers.
extern "C" and extern "C++" function declarations In C++, when used with a string, extern specifies that the linkage conventions of another language are being used for the declarator(s). C functions and data can be accessed only if they're previously declared as having C linkage.
It's telling the compiler that function signatures should be C compatible. Name mangling are different in C and C++ (i.e. C++ supports method overloading while C does not) so in order to make some function calls (i.e. some DLL dynamic calls) compatible with C signature, you use extern C
in C++ code.
Take a look at this StackOverflow question for a great explanation on the topic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With