hi, i was reading some code and came across this in a header file:
what does that mean? It's there so that the code can be compiled as c++?Code:#ifdef __cplusplus extern "C" { #endif ... #ifdef __cplusplus } #endif
hi, i was reading some code and came across this in a header file:
what does that mean? It's there so that the code can be compiled as c++?Code:#ifdef __cplusplus extern "C" { #endif ... #ifdef __cplusplus } #endif
:wq
> It's there so that the code can be compiled as c++?
No, its so some C++ code can call some other code which was compiled with C
uh, yes..
c++ compilers will define __cplusplus automatically
and if it's defined it gets compiled everything between #ifdef __cplusplus and #endif
will get compiled.
the extern "C" prevents name mangling of functions
i seem to have GCC 3.3.4
But how do i start it?
I dont have a menu for it or anything.
so, if i write a c++ prog that calls some functions from this library (it's a string library source code), it will work? and if the extern "C" is not there it won't?
:wq
Its there because of something called name mangling. Lets say you have a header like this:
Example:
Your C compiler will call those functions _draw_screen and _process_input, respectively.Code:#ifndef MY_HEADER #define MY_HEADER 1 void draw_screen(void); void process_input(int key); #endif
Now your C++ compiler may desire to call them _draw_screen10239814023984@LYWEORuijk02394u8 and _process_input203948kl2430@a029384LKJSf09234.
By changing the header to this:
Example:
You are telling your C++ compiler that it needs to link to _draw_screen, not _draw_screen10239814023984@LYWEORuijk02394u8.Code:#ifndef MY_HEADER #define MY_HEADER 1 #ifdef __cplusplus extern "C" { #endif void draw_screen(void); void process_input(int key); #ifdef __cplusplus } #endif #endif
> so, if i write a c++ prog that calls some functions from this library (it's a string library source code), it will work? and if the extern "C" is not there it won't?
Perhaps, but given the fact that I'm willing to bet that this library is written in C, no. Not only that, but its good practice to make sure you use extern "C" in libraries so that the functions have a predictable name. However its not really required since compiled libraries are not usually portable, you would just recompile the library with the new compiler. Name mangling varies from compiler to compiler. If the library is meant to be compiled in C, you will have to use the extern "C" no matter what when calling it from the C++ code since otherwise your C++ code will export calls to the name mangled version of the function. Your linker will get lost and die.