7

I see some code in C++ using extern "C" at the beginning of the file like this:

#ifdef __cplusplus 
extern "C" {} 
#endif

What does this mean? How does it work?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    Good information on extern "c" here: http://stackoverflow.com/questions/1041866/what-does-extern-c-in-c-source – Chen Harel Feb 08 '12 at 09:22

4 Answers4

5

It is used to inform the compiler to disable C++ name mangling for the functions defined within the braces. http://en.wikipedia.org/wiki/Name_mangling

ksming
  • 1,422
  • 1
  • 16
  • 26
4

It's probably not like that, but more like:

#ifdef __cplusplus 
extern "C" {
#endif

//some includes or declarations

#ifdef __cplusplus 
}
#endif

It tells the compiler to use C name mangling for whatever is declared inside the directives.

The way you have it now:

#ifdef __cplusplus 
extern "C" {} 
#endif

is just dead code.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • but the code I saw is:#ifdef __cplusplus extern "C" {} #endif , so is it wrong code? –  Feb 08 '12 at 09:21
  • 1
    @ratzip it's not wrong, it's just dead code. It does nothing. – Luchian Grigore Feb 08 '12 at 09:23
  • 3
    It tells the compiler (not the linker) to use C conventions for the functions, rather than C++. This involves not only name mangling, but the conventions for passing arguments, and possibly other things as well. – James Kanze Feb 08 '12 at 09:24
  • @JamesKanze are you saying the linker doesn't need to know about name mangling? – Luchian Grigore Feb 08 '12 at 09:29
  • Not at all. The compiler mangles names. The linker joins up whatever names it's given to whatever names its's asked-for. – spraff Feb 08 '12 at 10:24
  • @LuchianGrigore Not necessarily. About the only time most linkers take name mangling into account is when outputting error messages. – James Kanze Feb 08 '12 at 10:42
0

It specifies a linkage specification.
It tells the linker how to link the code.

It is useful when you want to mix C and C++ code.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

Extern "C" - notify the compiler,that the noted function is compiled in C style.

Oyeme
  • 11,088
  • 4
  • 42
  • 65