08 March, 2011

#ifdef __cplusplus

#ifdef __cplusplus
extern "C" {
#endif

.............
............
. .
.
.
.
#ifdef __cplusplus
}
#endif

i have seen this piece of code in many files esp in header files... any idea what does this mean and when to use this????

2 comments:

  1. Dude from what I Googled I understood that __cplusplus is defined by the C++ compiler.
    This allows you to check if the code is being compiled by a C comiler or a C++ compiler by adding an ifdef.

    If a C compiler is used then the macro __cplusplus is not defined any where in the code so the extern "C" { statement is bypassed by your ifdef.

    But if u attempt to compile the same code using a C++ compiler then the extern "C" { and } gets wrapped around your code.

    This is used to tell the C++ compiler that the enclosed code is a C code and C++ features like name mangling of functions (Function over loading) are not to be used.

    It just allows you to compile the code using any compiler.

    Try this...

    #include stdio.h

    #ifdef __cplusplus
    extern "C" {
    #endif

    int main()
    {
    #ifdef __cplusplus
    printf("Was compiled using C++ compiler\n");
    #else
    printf("Was compiled using a C compiler\n");
    #endif

    return 0;
    }

    #ifdef __cplusplus
    }
    #endif

    Compile using gcc and g++ and check the output... :)

    ReplyDelete
  2. i think you are correct... thanks AK...

    ReplyDelete