3

I read about the SIOF in the faq-lite and still I really don't understand why the issue happens. I have a static library(.a) and I use that library to use its static const data member object type. Then that static const data member object type I use and assign to a global variable(object). But it seems that global variable is empty when I use that global variable to my main or to any local function. I know obviously that my issue is SIOF but I really don't understand why my static const data member object was not initialized.

It was static library so I guess when we created our static library the static const data member object was compiled and linked to that static library, correct me if I'm wrong..

//libsource.h
class foo
{
   public:
   ....

   public:
   static const barbar foofaa;
};

//libsource.cpp
const barbar foo::foofaa = barbar();

//main.cpp
#include <libsource.h>

barbar foos= foo::foofaa;

int main()
{
   //can't use foos because its empty
}

Please advice. Why that static const data member object was not initialized even if its in the static library?

Many thanks.

dthorpe
  • 35,318
  • 5
  • 75
  • 119
domlao
  • 15,663
  • 34
  • 95
  • 134

1 Answers1

4

The static initialization order fiasco is fairly straightforward: static objects in a single translation unit are initialized in the order in which they are declared, but there is no guarantee as to the order in which static objects in different translation units are initialized with respect to each other.

So, in your specific example, foos in main.cpp may be initialized before foo::foofaa, which is declared in libsource.cpp.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • Hi Thanks. Its really blur to me about the initialization part. Why it needs to initialize the static data member? Does it already initialized when we compiled and linked to create a static library? Please advice. Thanks – domlao Jan 19 '11 at 02:31
  • 1
    @sasayins: static variables are not initialized until you run your program. They are not sitting around "pre-initialized" in your static library waiting to be used. Therefore, when your program begins (before `main()` is called) it initializes _all_ the static variables in every library. – JaredC Jan 19 '11 at 03:00
  • 1
    @JaredC: more precisely, some static variables are pre-initialised at compile or link time, but others (non-trivial ones) often need run-time initialisation. The compiler typically creates an initialisation function for each object it builds, then they're all called before main() is started, but the problem is that the order in which those initialisation functions are called may not be what your program needs. Indeed, if you have cyclic dependencies, than it may not matter which runs first - it will still be broken. The FAQ lite continues with some workarounds.... – Tony Delroy Jan 19 '11 at 05:35