为什么 extern 可以应用于定义?
为什么这是合法的?
extern int foo = 0xF00; // Gets a warning, still compiles
extern void bar() { // No warning
int x;
}
有理由允许这样做吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有时它很有用
如果没有
extern
,在 C++ 中foo
将是static
并具有内部链接(这意味着您不能使用foo< /code> 来自另一个翻译单元)。
在您的示例中,这两种情况下的
extern
都是多余的。 在 C99 中,extern
可以对内联
函数产生影响。。Sometimes it's useful
Without the
extern
, in C++foo
would bestatic
and have internal linkage (which means you could not usefoo
from another translation unit).The
extern
in both cases in your example is redundant. In C99 anextern
can make a difference forinline
functions..在函数的情况下,我认为这就像编写:
必须是合法的,因为具有定义的文件可能包含带有此类声明的标头。
In the function case, I think it is just like writing:
which must be legal since a file with the definition may include a header with such a declaration.
IIUC,在 C 标准中,定义就像带有初始值设定项的声明一样,因此适用于声明的所有内容同样适用于定义。
(实际上,定义是为变量分配存储空间的声明,因此 C 的暂定定义(没有初始值设定项)将符合资格,而那些充当定义但没有初始值设定项的 C++ 声明也将符合资格。定义本质上是一个声明加上一些添加的行为仍然适用)。
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).