Externing functions in C++
When externing a function in the cpp file does the compiler treat these differently?
extern void f开发者_JS百科oo(char * dataPtr);
void foo(char *);
extern void foo(char * );
I am wondering because I have see all these in code and not sure what the difference is.
Case by case:
extern void foo(char * dataPtr);
functions have external linkage by default, so the extern is not necessary - this is equivalent to:
void foo(char * dataPtr);
Parameter names are not significant in function declarations, so the above is equivalent to:
void foo(char * );
Use whichever you feel happiest with.
No. They all are same functions. There is only one function, namely with this signature:
void foo(char *);
Presence of other two makes no difference, with or without the keyword extern
, as function names have external linkage by default.
extern
is the default linkage for C++ functions. There's no difference between those three declarations.
No, they are the same. All function declarations are external. The extern keyword says "I want to let you know this exist, but I'm not defining it here." With an int, this would be necessary, because a declaration is also a definition. With a function, the semicolon at the end is explicitly marking it as not defined here.
My best guess as to why they marked it extern is possibly because the function declaration is in the header file but the definition is not in the corresponding c file as one would usually expect. This is similar to how extern is usually used on an int type (where you want to declare it but you plan to link it in from some other source.) So it's a form of documentation.
This is the best explanation of linkage to me:
http://publications.gbdirect.co.uk/c_book/chapter4/linkage.html
精彩评论