简体   繁体   English

关于匿名命名空间和内部链接的标准是什么?

[英]What standard says about anonymous namespace and internal linkage?

I'm curious about this fact as I came up with the following code:我对这个事实很好奇,因为我想出了以下代码:

namespace
{
    int my_variable = 12;
    void get_data_a_lot() {}
}


int main()
{
    my_variable++;

    get_data_a_lot();
}

and compiling with msvc I get the following:并使用 msvc 编译我得到以下信息:

00E 00000000 SECT4  notype       External     | ?my_variable@?A0x087c0a53@@3HA (int `anonymous namespace'::my_variable)
025 00000000 SECT6  notype ()    Static       | ?get_data_a_lot@?A0x087c0a53@@YAXXZ (void __cdecl `anonymous namespace'::get_data_a_lot(void))

But when I compile with gcc I get the following:但是当我用 gcc 编译时,我得到以下信息:

002 00000000 SECT2  notype       Static       | _ZN12_GLOBAL__N_111my_variableE
003 00000000 SECT1  notype ()    Static       | _ZN12_GLOBAL__N_114get_data_a_lotEv

So the question is: Is it correct behavior that "my_variable" is External or is it compiler bug?所以问题是:“my_variable”是外部的还是编译器错误是正确的行为?

The standard says标准说

[basic.link] [基本链接]

4 An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage. 4未命名命名空间或在未命名命名空间内直接或间接声明的命名空间具有内部链接。 All other namespaces have external linkage.所有其他命名空间都有外部链接。 A name having namespace scope that has not been given internal linkage above has the same linkage as the enclosing namespace if it is the name of如果名称是以下名称,则具有名称空间范围的名称未在上面给出内部链接与封闭名称空间具有相同的链接

  • a variable;一个变量; or或者
  • [...] [...]

According to which my_variable should have internal linkage.根据哪个my_variable应该有内部链接。 One must bear in mind however that how linkage is implemented is entirely up to the implementation.然而,必须记住,如何实现链接完全取决于实现。 The fact MSVC doesn't tag the symbol Static doesn't mean it's in violation of the standard. MSVC 没有标记符号Static事实并不意味着它违反了标准。 All the standard requires is an entity whose name has internal linkage is distinct from entities with the same name in other TU's, such that it can only be referred to by that name in the single TU it's defined in. The name mangling could very well be how MSVC easily accomplishes it.标准所要求的只是一个实体,其名称具有内部链接,与其他 TU 中具有相同名称的实体不同,因此只能在定义它的单个 TU 中通过该名称引用。名称修饰很可能是MSVC 如何轻松完成它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM