alvaro
alvaro

Reputation: 35

cross-initialization of global (extern) variables

I have a problem understanding how the compiler/linker generates the actual code when initializing variables that have a cross-file scope (extern). I mean, in what order these are instantiated? This seems problematic when at least one of the variables is defined using some other... For instance, this works as expected:

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;

The OUTPUT IS:

varA = 1   --> as expected!!
varB = 1   --> as expected!!

Now, the following which is slightly more complicated gives an unexpected result:

classB.h file:

#ifndef H_classB
#define H_classB

class classB {
public: 
    classB();
    int varB;
};

#endif

classB.cpp file:

#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 file:

#ifndef H_classA
#define H_classA

class classA {
public: 
    classA();
    int varA;
};

#endif

classA.cpp file:

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

In this case, the OUTPUT IS:

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

What's the rationale behind this behavior?

Upvotes: 1

Views: 219

Answers (1)

user2116939
user2116939

Reputation: 454

This is implementation-defined and recommended to avoid whenever possible.

Upvotes: 2

Related Questions