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?
The c++ language is allergic to adding new keywords so some get reused to mean different things.
externis one of these re-used keywords. It has 3 possible meanings: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:and
reciprocalwill be automatically be markedextern. Adding an extraexternhas no effect and is required for the C version which doesn't have theextern "C"wrapper.Note that if you are using single declaration version of
extern "C"then using a secondexternis not valid:As the second
externis not required the correct declaration is: