extern declaration and function definition both in the same file

核能气质少年 提交于 2019-12-04 02:51:39

You are misunderstanding the extern - it does not tell the compiler the definition is in another file, it simply declares that it exists without defining it. It's perfectly okay for it to be defined in the same file.

C has the concept of declaration (declaring that something exists without defining it) and definition (actually bringing it into existence). You can declare something as often as you want but can only define it once.

Because functions have external linkage by default, the extern keyword is irrelevant in this case.

Functions are implicitly extern in C. Including extern is just a visual reminder. Side note, to make a function not extern you can use the static keyword.

In a function declaration, extern simply declares that the function has external linkage, which is the default; the extern keyword is utterly useless in this context, and the effect is identical to a normal declaration/prototype without the extern keyword.

The warnings likely suggested a function prototype was missing. That's all.

The definition of the main function:

int main(int argc, char **argv) { ... }

is already a declaration is the prototyped syntax of the function main with external linkage. This means a prototyped declaration with extern just before the main definition is redundant.

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