[英]Static initializer of shared library inside dynamic library
So I have a static library (MacOS, .a library). 所以我有一个静态库(MacOS,.a库)。 It's written in C++ and has static initializers in it's code like that:
它是用C ++编写的,并且在它的代码中有静态初始化器:
//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. 我正在将.dylib库链接到这个.a lib。 Unfortunately, when my .dylib file is loaded, no
MyClass::newInitialDefaultValue()
is get called. 不幸的是,当加载我的.dylib文件时,不会调用
MyClass::newInitialDefaultValue()
。 What could be the reasons and how to deal with this? 可能是什么原因以及如何处理这个问题?
I've tried -all_load
and -force_load
linker flags with no luck. 我已经尝试了
-all_load
和-force_load
链接器标志而没有运气。
The all_load and force_load linker flags only ensure that the code is linked into the binary. all_load和force_load链接器标志仅确保代码链接到二进制文件。 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. 我认为你可以依赖的唯一保证是,在调用同一个cpp文件中的任何其他代码之前,将调用myclass.cpp中的初始化程序。 You need to expose access to your default via a function.
您需要通过函数公开对默认值的访问。 This would be similar to the Singleton pattern.
这与Singleton模式类似。 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. 现在,加载库时,defaultValue_仍然不会自动初始化。 But since the only access callers have is through getDefaultValue(), it is guaranteed to be initialized when they access it.
但由于唯一的访问调用者是通过getDefaultValue(),因此可以保证在访问它时进行初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.