Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use 'extern "C++"'?

Tags:

c++

c

In this article the keyword extern can be followed by "C" or "C++". Why would you use 'extern "C++"'? Is it practical?

like image 455
Les Avatar asked Mar 04 '09 14:03

Les


People also ask

Do you need extern C?

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.

What is the use of extern C in C++?

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.

Why do I sometimes need to use extern C {} In C++ header files?

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.

How do you use extern?

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.


2 Answers

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.

like image 51
Thomas L Holaday Avatar answered Oct 20 '22 02:10

Thomas L Holaday


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.

like image 41
James Curran Avatar answered Oct 20 '22 04:10

James Curran