Why can extern be applied to definitions?

ε祈祈猫儿з 提交于 2019-12-10 02:41:55

问题


Why is this legal?

extern int foo = 0xF00; // Gets a warning, still compiles

extern void bar() { // No warning
  int x;
}

Is there a reason to why this is allowed?


回答1:


Sometimes it's useful

extern const int foo = 0xF00;

Without the extern, in C++ foo would be static and have internal linkage (which means you could not use foo from another translation unit).

The extern in both cases in your example is redundant. In C99 an extern can make a difference for inline functions..




回答2:


In the function case, I think it is just like writing:

extern void bar();
void bar()
{
  int x;
}

which must be legal since a file with the definition may include a header with such a declaration.




回答3:


IIUC, in the C standard, a definition is treated just like a declaration with an initializer, so everything that applies to declarations applies equally to definitions.

(Actually, a definition would be a declaration that allocates storage for a variable, so C's tentative definitions (which don't have initializers) would qualify, and those C++'s declarations that act as definitions without having initializers would also qualify. The point that a definition is essentially a declaration plus some added behaviour still applies).



来源:https://stackoverflow.com/questions/7866692/why-can-extern-be-applied-to-definitions

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