问题描述
fileA.cpp:
fileA.cpp:
#include <iostream> extern int iA; extern int iB= iA; int main() { std::cout<<iA<<','<<iB; }
fileB.cpp
fileB.cpp
extern int iB; extern int iA = 2*iB;
编译和链接并运行,在调试和发布模式下进入 0,0
我的问题是它是如何工作的,为什么在链接阶段没有问题?
我使用VC ++ 2003。
Compiled and linked and ran, out come in the debug and release mode is 0,0My question is how it works, why there is no issue in linking stage?I'm using VC++2003.
推荐答案
初始化器覆盖 extern 关键字,所以没有什么神奇关于这一点:你只是声明和定义两个完全不相关的变量在不同的函数。
The initialiser overrides the extern keyword, so there's nothing "magical" about this: you're just declaring and defining two completely unrelated variables in different functions.
:
fileA.cpp
#include <iostream> extern int iA; int iB= iA; int main() { std::cout<<iA<<','<<iB; }
fileB.cpp
$ b
fileB.cpp
extern int iB; int iA = 2*iB;
现在,两个对象都必须在发生其他事情之前进行静态初始化(按位全零)。当动态初始化稍后发生时,取决于fileA.cpp或fileB.cpp中的静态存储持续时间对象是否首先被初始化(并且你不知道将是什么顺序) 初始化为零 iA (然后 iA 按预期初始化为 2 * iB 或 iA 初始化为零 iB 乘以2,仍然是2(然后 iB 初始化为零 iA )。
Now, both objects necessarily undergo static initialization (to bitwise all-zeroes) before anything else happens. When dynamic-initialization later takes place, depending on whether the static-storage-duration objects in fileA.cpp or fileB.cpp get initialised first (and you can't know what order that'll be) either iB is initialized to a zero iA (then iA is initialized to 2*iB as expected), or iA is initialised to a zero iB multiplied by two, which is still two (then iB is initialized to a zero iA).
无论哪种方式,两个对象都将通过定义好的语义结束,值为零。
Either way, both objects are going to end up, via well-defined semantics, having a value of zero.
这篇关于扭曲逻辑:一个文件中的全局变量指的是extern变量,但也由该extern变量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!