Suppose I have the following files:
#ifndef A_H
#define A_H
#include <vector>
class A {
public:
static int add( int x );
static int size();
private:
static std::vector<int> vec;
};
#endif
#include "A.h"
std::vector<int> A::vec;
int A::add( int x ) {
vec.push_back( x );
return vec.size();
}
int A::size() {
return vec.size();
}
#ifndef B_H
#define B_H
class B {
public:
static const int val = 42;
};
#endif
#include "B.h"
#include "A.h"
int tempvar = A::add( B::val );
#include <iostream>
#include "lib/A.h"
#include "lib/B.h"
int main() {
std::cout << A::size() << std::endl;
}
The result of this code differs depending on how I compile it:
g++ main.cpp lib/A.cpp lib/B.cpp -o nolibAB
./nolibAB
prints "1"
g++ main.cpp lib/B.cpp lib/A.cpp -o nolibBA
./nolibBA
prints "0"
g++ -c lib/A.cpp lib/B.cpp
ar rvs lib.a A.o B.o
g++ main.cpp lib.a
./a.out
prints "0" (regardless if I reorder A.cpp and B.cpp)
Can someone tell me the reason that this is the case?
EDIT: I use gcc 4.6.1
This is undefined by the standard. Simply put: You should not rely on global variables being initialized in a certain order.
Related: Static initialization order issue in C++
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With