0

So I have a static library (MacOS, .a library). It's written in C++ and has static initializers in it's code like that:

//myclass.hpp
class MyClass {
    ...
    static MyClass *defaultValue_;
    static MyClass *newInitialDefaultValue();
    ...
}
...
//myclass.cpp
MyClass *MyClass::defaultValue_ = newInitialDefaultValue();
...

I'm linking my .dylib library against this .a lib. Unfortunately, when my .dylib file is loaded, no MyClass::newInitialDefaultValue() is get called. What could be the reasons and how to deal with this?

I've tried -all_load and -force_load linker flags with no luck.

peetonn
  • 2,942
  • 4
  • 32
  • 49

1 Answers1

2

The all_load and force_load linker flags only ensure that the code is linked into the binary. I don't think these flags will help you.

The only guarantee that I think you can count on is that your initializer in myclass.cpp will be called before any other code in the same cpp file is called. You need to expose access to your default via a function. This would be similar to the Singleton pattern. For example:

//myclass.hpp
class MyClass {
    ...
    static MyClass *getDefaultValue();
    ...
}
...
//myclass.cpp
static MyClass* defaultValue_; // Note that this is not a member variable
MyClass* MyClass::getDefaultValue() {
   if (defaultValue_ == nullptr) {
       defaultValue_ = newInitialDefaultValue(); 
   }
   return defaultValue_;
}   
...

NOTE: I made no attempt to make this thread safe or handle errors.

Now, the defaultValue_ still will not be automatically initialized when the library is loaded. But since the only access callers have is through getDefaultValue(), it is guaranteed to be initialized when they access it.

sbaker
  • 437
  • 2
  • 7
  • thanks for you insights very much! unfortunately, the error was in build system of library which with new version placed library binaries in different location, and i was still using the old lib binaries. it happens... – peetonn Aug 06 '13 at 19:11