gpt4 book ai didi

c++ - "internal linkage"是什么意思?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:58 25 4
gpt4 key购买 nike

在标准中它说:

When a name has internal linkage , the entity it denotes can be referred to by names from other scopes in the same translation unit.

和:

A name having namespace scope (3.3.6) has internal linkage if it is the name of — a variable, function or function template that is explicitly declared static;

因此请考虑以下代码:

#include <stdio.h>

namespace A
{
/* a with internal linkage now.
Entity denoted by a will be referenced from another scope.
This will be main() function scope in my case
*/
static int a=5;
}

int main()
{
int a; //declaring a for unqualified name lookup rules
printf("%d\n",a);//-1216872448
}

我真的不明白标准中的定义。这是什么意思:

the entity it denotes can be referred to by names from other scopes in the same translation unit.

最佳答案

A translation unit通常由包含所有 #include 的单个源文件组成d 个文件并将结果放入一个目标文件

命名空间范围中的名称默认具有外部链接,这意味着您可以从其他翻译单元引用该名称(使用范围解析运算符或使用指令)。但是如果名字是用 static 限定的, 链接变为内部,并且不能在定义它的翻译单元之外引用该名称。

在您的示例中,您可以访问 a如果命名空间 A , 名字 amain方法在相同翻译单元中。但是在main ,您正在声明另一个变量 a ,它隐藏了 a在命名空间 A .和 a in main 未初始化,因此当您打印时,它实际上打印来自 a 的垃圾值在 main 中声明.如果你想使用 a来自 Amain ,像cout<<A::a一样使用或使用 using namespace A;在包含 main 的源文件中.

关于c++ - "internal linkage"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23645495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com