Search code examples
c++cmacos

__cplusplus compiler directive defined and not defined


I'm having a problem with eclipse CDT.

There I am having a C++ project that uses the C FatFs library. I'm trying to implement the fatfs files. Question: In multiple files, I'm adding this wrapper:

#ifdef __cplusplus 
extern "C" 
{ 
#endif 

// code..

#ifdef __cplusplus
}
#endif

But for some reason, in the one .h file __cplusplus is defined, and in the other .h file __cplusplus is not defined.

Any suggestions?


Solution

  • Look here: Combining C++ and C — how does #ifdef __cplusplus work?

    extern "C" doesn't really change the way that the compiler reads the code. If your code is in a .c file, it will be compiled as C, if it is in a .cpp file, it will be compiled as C++ (unless you do something strange to your configuration).

    What extern "C" does is affect linkage. C++ functions, when compiled, have their names mangled -- this is what makes overloading possible. The function name gets modified based on the types and number of parameters, so that two functions with the same name will have different symbol names.

    Code inside an extern "C" is still C++ code. There are limitations on what you can do in an extern "C" block, but they're all about linkage.

    Also, you probably want two #ifdef __cpluspluss:

    #ifdef __cplusplus 
    extern "C" { 
    #endif 
        // ...
    #ifdef __cplusplus
    }
    #endif
    

    Otherwise, your C code will never see your definitions.