Use of extern "C" with global variables
Hi,
Over the years had thought that extern "C" was used to prevent C++ compilers from mangling function names - to allow calls from C code to C++ code. Name mangling was introduced in C++ compilers for the purpose of support for function over-riding.
However, I have come across code where extern "C" has been used to declare global variables in a file. I thought global variables had nothing to do with name mangling - besides I am used to seeing only the extern keyword to declare global variables.
Can you please let me understand the reason why extern "C" would need to be used with global data variables too ?
Re: Use of extern "C" with global variables
Variables, global or not, can be mangled too... think of those belonging to a namespace! When you use extern keyword, the variable is being shared across translation units. When you use __dllspec(dllexport), it is being exported by the module. When mixed C / C++ implementations, extern "C" would be required.
Best regards,
Re: Use of extern "C" with global variables
Thank you Bornish. The concept of namespaces also introduces name mangling - missed that point.
Re: Use of extern "C" with global variables
Re: Use of extern "C" with global variables
It is to signal the compiler that the symbol (the variable) has external linkage, that it may be being used in other compilation units.