The C ++ standard library faces the same problem: it must ensure that cin , cout , etc. initialized before any code uses them, including constructors for static objects. The trick that was invented to solve this situation can also solve your problem. In the header file, which includes the first in each translation unit (well, each translation unit that has static objects with dynamic initializers):
class init_library { public: init_library() { if (counter++ == 0) initilaize_the_library(); } private: static int counter; }; static init_library i_library;
and in one translation unit you must provide the definition init_library::counter .
This will result in a static object of type init_library in each translation unit that is pulled into the header. Its initialization will occur before any other initialization in the same translation unit (since its #include directive appeared first - do not forget about it!), And for the first time one of these objects is initialized, it will call the code to initialize the library. (Note that this code is not thread safe, which makes it thread safe directly)
This is called a "great trick."
Pete becker
source share