Externing functions in C++

﹥>﹥吖頭↗ 提交于 2020-02-02 02:03:06

问题


When externing a function in the cpp file does the compiler treat these differently?

extern void foo(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.


回答1:


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.




回答2:


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.




回答3:


extern is the default linkage for C++ functions. There's no difference between those three declarations.




回答4:


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



来源:https://stackoverflow.com/questions/6218793/externing-functions-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!