gpt4 book ai didi

c++ - 在不同的翻译单元中启动全局变量(涉及链接器)

转载 作者:行者123 更新时间:2023-11-30 05:02:10 27 4
gpt4 key购买 nike

我最近正在复习 C++。这是我的问题。请参阅 file1.cppfile2.cpp 中的代码。

文件1.cpp

int x1 = 1;
int y1 = x1 + 2;

文件2.cpp

#include "necessary_headers"
extern int y1;
int y2 = y1 + 2;
int main()
{
cout << "y2 is "<<y2<<endl;
return 0;
}

我以不同的顺序编译:

gcc file1.cpp file2.cpp

当然,输出是 y2 is 5

gcc file2.cpp file1.cpp 

输出是y2 is 2。(我的问题是关于这个的)

我也试试这个:gcc file2.cpp。当然,这会给出 对 y1 的 undefined reference

我的问题是,即使链接序列“错误”,为什么 gcc file2.cpp file1.cpp 编译而不是给出 undefined reference to y1 错误?是不是因为在链接 file2.cpp 时,链接器很聪明地引用了在以下文件 file1.cpp 中定义的 y1?而这样,y1file2.cpp中被初始化为0(默认值),而不是使用file1.cpp中的定义?那么这样一来,file1.cpp "int y1 = x1 + 2" 中的定义和初始化不是被链接序列作废了吗?如果不是,我如何执行该语句来分配 y1 = x1 + 2?最后,这是一般的编译器行为吗?根据c++标准,不同翻译单元初始化全局变量的顺序是不确定的。

感谢您的帮助!真的很感激。

最佳答案

My question is, why would gcc file2.cpp file1.cpp compile rather than giving undefined reference to y1 error even if the linking sequence is "wrong"?

来自 basic.link#2.1

When a name has external linkage, the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.

因此,如果您编译包含 y1 定义的文件(例如 file1.cpp),则 extern int y1; 不是未定义的。

在链接过程中,y1 的定义是从其他翻译单元检查的。

关于c++ - 在不同的翻译单元中启动全局变量(涉及链接器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50013784/

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