Is extern "C" only required on the function declaration?
Edit:
Seems like I had misunderstood the question.
Anyways, I tried:
// foo.cpp
/* Function definition */
#include "foo.h"
void foo(int i) {
//do stuff
}
void test(int i)
{
// do stuff
}
// foo.h
#ifdef __cplusplus
extern "C" {
#endif
/* Function declaration */
void foo(int);
#ifdef __cplusplus
}
#endif
void test(int);
Using command nm
to view the symbols from the compiled file:
linuxuser$ nm foo.o
00000006 T _Z4testi
U __gxx_personality_v0
00000000 T foo
This clearly suggests that the name of function declared as extern "C" is not mangled and the extern "C" keyword is not required at definition.
Had it required every C library code written without extern "C" would have been unusable in C++ programs.
The 'extern "C"
' should not be required on the function defintion as long as the declaration has it and is already seen in the compilation of the definition. The standard specifically states (7.5/5 Linkage specifications):
A function can be declared without a linkage specification after an explicit linkage specification has been seen; the linkage explicitly specified in the earlier declaration is not affected by such a function declaration.
However, I generally do put the 'extern "C"
' on the definition as well, because it is in fact a function with extern "C" linkage. A lot of people hate when unnecessary, redundant stuff is on declarations (like putting virtual
on method overrides), but I'm not one of them.