共享库结合才库不处理
问题描述:
我有一个共享图书馆的共享库结合才库不处理
以下问题创建一个共享libraray
class A
{
static int callCount;
A() { callCount++; }
}
int A:callCount = 0;
class Main
{
Main()
{
A a1();
A a2();
}
}
现在创建它加载此共享libraray多次,我会的过程像有callCount只属于共享库而不是整个过程
dlopen("shared.so", RTLD_LAZY);
// after some code i can construct Main()
// and now i will open the shared object again
dlopen("shared.so", RTLD_LAZY);
// now if i construct Main from the new library i want to have a new
// initialized callCount eq 0 but its 2
我怎样才能解决这个问题
答
加载,尤其是重新加载运行时加载库的语义是非常平台和特定于实现的。最好不要依赖任何类型的全局状态,而是将明确的初始化函数传递给库。也许像这样:
library_context_t context;
/* dlopen, dlsym, ... */
library_init(&context);
library_do_thing(&context);
// ...
library_destroy(&context);
// maybe unload, or reuse
Linux的特别不不重新加载已经加载的库。