2009-10-21 26 views

回答

21

圖書館應該導出初始化 並用gcc __attribute __((構造函數))和__attribute __清理例程((析構))函數屬性。有關這些信息,請參閱gcc信息頁面 。構造函數 例程在dlopen 返回之前執行(或者在main()之前啓動 如果庫在加載 時加載)。在dlclose返回之前執行的析構函數例程爲 (或者,如果在加載 時加載了庫,則在退出()或完成main()後退出 )。這些 函數的C原型是:

void __attribute__ ((constructor)) my_init(void); 
void __attribute__ ((destructor)) my_fini(void); 

http://tldp.org/HOWTO/Program-Library-HOWTO/index.html

也就是說,你只是釘在__attribute__((構造函數))帶到你要調用的函數時共享庫被加載。上述文件還指出,舊的_ini和_fini函數被認爲是過時的。

+0

最有幫助......謝謝! – jldupont 2009-10-21 17:59:36

+1

注意:非常不便攜。 – Noldorin 2014-12-23 17:16:32

0

至少在Linux上,並且可能在至少一些其他Unix系統上,如果動態鏈接庫將動態打開一個名爲_init的全局函數(如果存在),該函數將被動態鏈接器調用。

+0

...這個_init函數的原型是什麼? – jldupont 2009-10-21 17:54:44

+3

@Jack:剛剛通過http://tldp.org/HOWTO/Program-Library-HOWTO/miscellaneous.html#INIT-AND-CLEANUP發現_init和_fini特殊功能被標記爲OBSOLETE/DANGEROUS ... – jldupont 2009-10-21 17:58:54

15

是的。當一個庫被打開,所有的靜態結構發生......所以,如果你使用C++,你可以這樣做:

 
// mylibrary.cpp 
namespace 
{ 
    class dynamic_library_load_unload_handler 
    { 
     public: 
       dynamic_library_load_unload_handler(){ 
        // Code to execute when the library is loaded 
       } 
       ~dynamic_library_load_unload_handler(){ 
        // Code to execute when the library is unloaded 
       } 
    } dynamic_library_load_unload_handler_hook; 
} 

給出不同的解決方案__attribute__ ((constructor)),這將是便攜。但請注意,如果您有多個這樣的對象,則無法保證構建/銷燬順序。

+0

有趣......謝謝! – jldupont 2009-10-21 21:28:45

+0

工程就像一個魅力:再次感謝。 – jldupont 2009-11-03 18:19:45

+0

你的回答太糟糕了...... – jldupont 2009-12-01 20:24:31

相關問題