0

WORKSPACE_A.cpp/.h

Class WORKSPACE_A {
   static AAA a;
}

WORKSPACE_B.cpp/.h

   Class WORKSPACE_B {
       static BBB b;
    }

How do I know whether AAA a , or BBB b is initialized first.

Thank you

Ben Hull
  • 7,524
  • 3
  • 36
  • 56
Denny
  • 449
  • 4
  • 17
  • you can't, you shouldn't care (you should just imagine that they are initialized at the same time) – Exceptyon Jan 15 '14 at 11:08
  • 1
    @Exceptyon Perhaps BBB b; has to call WORKSPACE_A:a in BBB::BBB() constructor – Denny Jan 15 '14 at 11:09
  • You should initialize the static variables in a cpp-file in any order you need. For example, `int WORKSPACE_A::a = 1; int WORKSPACE_B::b = 2;`. Also you may move all initialization in a method and use `#pragma`s to run it at initialization. The pragmas may vary depending from your compiler: `#pragma startup` and `#pragma init_seg` are to name a few. – Stan Jan 15 '14 at 11:40

4 Answers4

1

As stated by @Denny the issue is probably dependencies between the twos.

I think the way to go is having pointers and explicit static init functions:

class WORKSPACE_A {
   static AAA* a;
public:
   static void initialize() { /* a = ... */ }
}

class WORKSPACE_B {
   static BBB* b;
public:
   static void initialize() { /* b = some_f(WORKSPACE::a) */ }
}
Exceptyon
  • 1,584
  • 16
  • 23
  • I know it could be fixed by your above code , that's no way to order initialzation right ? , can I order file when linking *.o ("cc workspace_a.o workspace_b.o to solve this problem ? – Denny Jan 15 '14 at 11:16
  • could be... depends on how your linker is implemented I guess... I wouldn't rely on that anyway: one day you'll forget to order the .o in a makefile, or change compiler – Exceptyon Jan 15 '14 at 11:31
1

This is called the "static initialization order fiasco"

A common approach is to use initialize-on-first-use within an "accessor function"

class WORKSPACE_A {

   AAA& getA()
   {
     static AAA a;
     return a;
   }
}

Of course, you still have "static destruction order fiasco" to contend with... This can be mitigated by dynamically allocating the AAA in the accessor (static AAA *a = new AAA;) but then the object simply never gets destructed!

Roddy
  • 66,617
  • 42
  • 165
  • 277
0

No.

The standard says that this is undefined.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

Order of initialization of global variables (or static) are guaranteed in each translation unit. But not guaranteed in different translation units.

See this answer to the question C++ global initialization order ignores dependencies?.

Community
  • 1
  • 1
Yousf
  • 3,957
  • 3
  • 27
  • 37