Click here to Skip to main content
15,886,639 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have been meeting the following in some c/c++ codes but I don't understand the theory behind it:

#ifdef __cplusplus
extern "C" {
#endif

I want to understand how it works. Someone teach me please!
Posted

By default, C++ mangles names: http://en.wikipedia.org/wiki/Name_mangling[^]

extern "C" tells the compiler not to mangle the names in that block. It is normally used for functions that are exported from a dll, so they can be used more easily from external code.

The #ifdef _cplusplus check is for the C++ compiler.

Nick
 
Share this answer
 
Standard C (non-C++) doesn't support this:
extern "C" {

So here's checked whether we are compiled under C++ or not:
#ifdef __cplusplus
 
Share this answer
 
That typically encloses DLL's exported functions.
You should know, C Language and C++ one use different approach to function's name mangling (i.e. altering the name of the funtion in object -or library- files), more specifically, C++ includes in the mangled (or decorated) name info about the function argument types (this allows, function overloads, a C++ feature, not available in C language).
The mechanism allows the same header to be used by both the C and C++ compiler ( __cpluspls macro is defined only by the C++ one) and works this way:
The C compiler, ignores the extern "C" (__cplusplus is not defined) directive both when building the DLL and when including the DLL header inside an application.

The C++ compiler, according with the extern "C" (__cplusplus is defined) directive:
  • Produces a standard C DLL (i.e. the function use the C language mangling scheme) when building th DLL.
  • consider the library as a C DLL when the header is included in a application (you know C++ compiler is able to link with C libraries).


BTW: please don't post your question both int the C++/MFC forum and here.
:)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900