How do input order files affect communication and static initialization in GCC?

Suppose I have the following files:

Library / Hijri

#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

Library /a.cpp

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

Library / Bh

#ifndef B_H
#define B_H

class B {
        public:
                static const int val = 42;
};

#endif

Library /B.cpp

#include "B.h"
#include "A.h"

int tempvar = A::add( B::val );

and finally: main: cpp

#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 of whether I reordered A.cpp and B.cpp)

Can someone tell me why this is?

EDIT: I am using gcc 4.6.1

+5
source share
1 answer

This is undefined by standard. Simply put: you should not rely on initializing global variables in a specific order.

Related: The problem of static initialization in C ++

+1

All Articles