c++externextern-c

Extern used twice in C++


I am very curious about what happens during linking, and, during my research in this area I have stabbed upon this code

#ifdef __cplusplus
extern “C” { 
#endif

extern double reciprocal (int i);

#ifdef __cplusplus
}
#endif

The code was in some header file, which was include by .c and .cpp source files of one program. It's a declaration of a function, which is then defined in .cpp file. Why does it work? I mean, during the compilation of the .cpp file this will turn into

extern "C" {
    extern double reciprocal (int i);
}

The outer extern both makes the function visible in the global scope and converts the C++ style of function names into C one. But there also is an inner extern. Is it OK the function is externed twice?


Solution

  • The c++ language is allergic to adding new keywords so some get reused to mean different things. extern is one of these re-used keywords. It has 3 possible meanings:

    1. external linkage - the variable or function is defined somewhere else
    2. language linkage - the variable or function is defined in an "external" language
    3. explicit template instantiation declaration

    In your case you are using 1 and 2. extern "C" declares that the code has "C" rather than the default "C++" linkage. This also implies external linkage so in pure C++ code you can just write:

    extern "C" {
        double reciprocal (int i);
    }
    

    and reciprocal will be automatically be marked extern. Adding an extra extern has no effect and is required for the C version which doesn't have the extern "C" wrapper.

    Note that if you are using single declaration version of extern "C" then using a second extern is not valid:

    extern "C" extern double reciprocal (int i);
    

    As the second extern is not required the correct declaration is:

    extern "C" double reciprocal (int i);