簡體   English   中英

全局(外部)變量的交叉初始化

[英]cross-initialization of global (extern) variables

在初始化具有跨文件范圍(外部)的變量時,我在理解編譯器/鏈接器如何生成實際代碼時遇到問題。 我的意思是,這些實例以什么順序實例化? 當使用其他變量定義至少一個變量時,這似乎是有問題的。例如,這按預期工作:

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;
}

在這種情況下,輸出為:

myA.varA = 0   --> WHY??? shouldn't it be 1? 
myB.varB = 1   --> as expected!

這種行為背后的原理是什么?

這是實現定義的,建議盡可能避免。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM