In this article the keyword extern can be followed by "C" or "C++". Why would you use 'extern "C++"'? Is it practical?
You need to use extern "C" in C++ when declaring a function that was implemented/compiled in C. The use of extern "C" tells the compiler/linker to use the C naming and calling conventions, instead of the C++ name mangling and C++ calling conventions that would be used otherwise.
The extern “C” keyword is used to make a function name in C++ have the C linkage. In this case the compiler does not mangle the function.
We had always only added extern "C" to the header definitions, but this allows the C++ code to implement the function with a different signature via overloading without errors and yet it doesn't mangle the symbol definition so at link times it uses this mismatching function.
the extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit. When extern is used with a variable, it's only declared, not defined.
The language permits:
extern "C" { #include "foo.h" }
What if foo.h contains something which requires C++ linkage?
void f_plain(const char *); extern "C++" void f_fancy(const std::string &);
That's how you keep the linker happy.
There is no real reason to use extern "C++"
. It merely make explicit the linkage that is the implicit default. If you have a class where some members have extern "C" linkage, you may wish the explicit state that the others are extern "C++".
Note that the C++ Standard defines syntactically extern "anystring"
. It only give formal meanings to extern "C"
and extern "C++"
. A compiler vendor is free to define extern "Pascal"
or even extern "COM+"
if they like.
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