当我在 VC++ 10 上编译以下源代码时,带有静态链接的 i
被分配给 42
但是在 G++ 4.5.1 上,source2.cpp 中带有外部链接的 i
被分配给 42
。
根据标准,关于什么应该是标准确认行为或为什么有任何想法?
// source1.cpp
#include <iostream>
static int i = 0;
int h();
void foo()
{
int i;
{
extern int i;
i = 42;
}
}
int main()
{
foo();
std::cout << i << std::endl;
std::cout << h() << std::endl;
}
// source2.cpp
int i;
int h() { return i; }
最佳答案
ISO/IEC 14882:2011 3.5/6:
The name of a function declared in block scope and the name of a variable declared by a block scope
extern
declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage.
在 foo()
的内部 block 中,声明 int i;
隐藏了全局命名空间范围内的声明:static int i;
所以在内部 block 中没有可见的带有链接的i
。这意味着 extern int i;
指的是命名空间中具有外部链接的实体,该命名空间立即包含 foo()
。
赋值应该影响带有外部链接的i
(在source2.cpp
中定义),它应该不会影响带有外部链接的i
source1.cpp
中定义的内部链接。
关于c++ - 具有外部链接的编译器的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8282018/