在初始化具有跨文件范围(extern)的变量时,我在理解编译器/链接器如何生成实际代码时遇到问题。我的意思是,这些实例化的顺序是什么?当使用其他一些变量定义至少一个变量时,这似乎有问题...例如,这可以按预期工作:
main.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;
}
variableA.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).
}
main.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;
}
在这种情况下,OUTPUT是:
myA.varA = 0 --> WHY??? shouldn't it be 1?
myB.varB = 1 --> as expected!
这种行为背后的理由是什么?
答案 0 :(得分:2)
这是实现定义的,建议尽可能避免。