2012-09-05 40 views
1

我有一個共享圖書館的共享庫結合才庫不處理

以下問題創建一個共享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 

我怎樣才能解決這個問題

回答

0

加載,尤其是重新加載運行時加載庫的語義是非常平臺和特定於實現的。最好不要依賴任何類型的全局狀態,而是將明確的初始化函數傳遞給庫。也許像這樣:

library_context_t context; 

/* dlopen, dlsym, ... */ 

library_init(&context); 

library_do_thing(&context); 

// ... 

library_destroy(&context); 

// maybe unload, or reuse 

Linux的特別不重新加載已經加載的庫。