c++ - 具有外部链接的编译器的不同行为

标签 c++ extern linkage

当我在 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/

相关文章:

c++ - std::vector - 如何释放 vector 中 char* 元素的内存?

c++ - 读取表示整数的 6 字节大端二进制字段

c++ - 如何用容器列表实现功能

c++ - 链接失败,怎么回事?

c++ - 在 const 成员函数中使用 this 指针 (C++)

c# - 如何设置一个 C++ 函数以便它可以被 p/invoke 使用?

c++ 全局变量未在此范围内声明

C++ 链接器提示 char* 的多个定义,但不是 std::string

c++ - STL 静态常量成员定义

c - 多个源文件中使用的结构 timespec : C