Suppose I have the following files:
lib/A.h
#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
lib/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();
}
lib/B.h
#ifndef B_H
#define B_H
class B {
public:
static const int val = 42;
};
#endif
lib/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 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