Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly do I lose when using extern "C" in C++? [duplicate]

I'm trying to develop a dynamic library in C++ to be called by an existing program written in IDL (Interactive Data Language). I know that I need to use extern "C" to disable name mangling so that IDL can call the functions it needs (the rest of the calling mechanism is pretty straightforward).

However, I'm always hesitant to use features of a language that I don't fully understand, so my question is this: What features of C++ do I lose by reverting to C linkage, if any? Namespaces would be an obvious one, I think, but does it completely disable all the other nice features of C++ too? Can I still use the C++ STL, and all the various language features (especially C++11 ones) that I've come to rely on? Or am I stuck essentially coding in C?

like image 427
user1871183 Avatar asked Dec 02 '12 23:12

user1871183


People also ask

What is the point of extern C?

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. In a template declaration, extern specifies that the template has already been instantiated elsewhere.

Can you use extern C in C?

By declaring a function with extern "C" , it changes the linkage requirements so that the C++ compiler does not add the extra mangling information to the symbol. This pattern relies on the presence of the __cplusplus definition when using the C++ compiler. If you are using the C compiler, extern "C" is not used.

How does C extern work?

Software Engineering C Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used access variables across C files.

Is extern necessary in C?

You do not necessarily "need" extern for variables. When C was invented Unix linkers were also written, and they advanced the art in unheralded but clever ways. One contribution was defining all symbols as small "common blocks".


1 Answers

The only thing that gets dropped is name mangling of externally visible names. Function overloading by parameter types, as well as by parameter count, stop working as the result. Essentially, name resolution during the linking phase goes back to the plain old C mode (i.e. one name - one entry).

As far as the internals of your implementation go, you can continue using the standard library and all the other nice features of C++11. Only the names of externally visible entities get changed by extern C.

like image 109
Sergey Kalinichenko Avatar answered Sep 28 '22 09:09

Sergey Kalinichenko