0

Possible Duplicate:
Combining C++ and C - how does #ifdef __cplusplus work?

I come across the following lines in many libraries; what are they good for? When/where is __cplusplus defined?

#ifdef __cplusplus
    extern "C" {
#endif

//...

#ifdef __cplusplus
    }
#endif
Community
  • 1
  • 1
mrk
  • 3,061
  • 1
  • 29
  • 34

1 Answers1

4

__cplusplus is defined for C++ code. It happens sometimes that you have to mix C code, and C++ code. There can be many reasons for that, e.g. you have a driver written long ago in C that you want to use in your brand new C++0x project.

Every function type and name has a language linkage. There's a difference between C adn C++ functions, since C does not have function names overloading, a function name can serve as a unique identifier in C, but can not in C++. This is called function mangling.

Since you don't need to mangle the name in C, using extern "C" will make the compiler omit adding the parameter information for linkage.

The C++ standard explicitly states in 7.5 para 3:

Every implementation shall provide for linkage to functions written in the C programming language, "C", and linkage to C++ functions, "C++".

complex sqrt(complex); //C++ linkage by default
extern "C" {
    double sqrt(double);//C linkage
}
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
  • @SingerOffTheFall Awesome, you can put whatever C code you want inside those brackets? What is 7.5 para 3? – mrk Sep 24 '12 at 11:58
  • @saad, yes that is used to include valid C code inside of C++. 7.5 paragraph 3 is a section of the standard which I quoted. – SingerOfTheFall Sep 24 '12 at 12:00
  • "lets you execute C code" is just nonsense. Everything in C++ is C++. `extern "C"` is just a linkage specifier. – Kerrek SB Sep 24 '12 at 12:03
  • @SingerOfTheFall Do you have a link to the standard? – mrk Sep 24 '12 at 12:05
  • @saad, the standard itself can be bought [here](http://www.iso.org/iso/catalogue_detail.htm?csnumber=50372), and you can't get it for free officially, however, you can find one of the latest drafts which are usually available for free, and do not differ much from the final version. – SingerOfTheFall Sep 24 '12 at 12:14