在初始化具有跨文件范围(extern)的变量时,我无法理解编译器/链接器如何生成实际代码。我的意思是,这些实例化的顺序是什么?当使用其他变量定义至少一个变量时,这似乎有问题......例如,这按预期工作:
主.cpp:
#include <iostream>
using namespace std;
extern int varA;
int varB=1;
int main ()
{
cout << "varA = " << varA << endl;
cout << "varB = " << varB << endl;
system ("pause");
return 0;
}
变量A.cpp
extern int varB;
int varA=varB;
输出是:
varA = 1 --> as expected!!
varB = 1 --> as expected!!
现在,以下稍微复杂一点的结果给出了意想不到的结果:
classB.h 文件:
#ifndef H_classB
#define H_classB
class classB {
public:
classB();
int varB;
};
#endif
classB.cpp 文件:
#include "classB.h"
classB myB; // defined => cross-file scope by using extern in other files
classB::classB() {
varB=1; // constructor initialized varB to 1
}
classA.h 文件:
#ifndef H_classA
#define H_classA
class classA {
public:
classA();
int varA;
};
#endif
classA.cpp 文件:
#include "classA.h"
#include "classB.h"
extern classB myB;
classA myA; // defined => cross-file scope by using extern in other files
classA::classA() {
varA=myB.varB; // constructor initialized varA to the value of the instance
// variable varB of the pre-instantiated object myB (defined
//in classB.cpp).
}
主.cpp:
#include <iostream>
using namespace std;
#include "classA.h"
#include "classB.h"
extern classA myA;
extern classB myB;
int main ()
{
cout << "myA.varA = " << myA.varA << endl;
cout << "myB.varB = " << myB.varB << endl;
system ("pause");
return 0;
}
在这种情况下,输出为:
myA.varA = 0 --> WHY??? shouldn't it be 1?
myB.varB = 1 --> as expected!
这种行为背后的原因是什么?