2010-09-02 48 views
7

我正在嘗試爲我編寫的程序製作一種插件體系結構,並且在第一次嘗試時遇到了問題。是否有可能從共享對象內的主要可執行文件訪問符號?我想下面的就可以了:共享對象無法在主要二進制文件中找到符號,C++

testlib.cpp:

void foo(); 
void bar() __attribute__((constructor)); 
void bar(){ foo(); } 

testexe.cpp:

#include <iostream> 
#include <dlfcn.h> 

using namespace std; 

void foo() 
{ 
    cout << "dynamic library loaded" << endl;  
} 

int main() 
{ 
    cout << "attempting to load" << endl; 
    void* ret = dlopen("./testlib.so", RTLD_LAZY); 
    if(ret == NULL) 
     cout << "fail: " << dlerror() << endl; 
    else 
     cout << "success" << endl; 
    return 0; 
} 

編譯時:

g++ -fPIC -o testexe testexe.cpp -ldl 
g++ --shared -fPIC -o testlib.so testlib.cpp 

輸出:

attempting to load 
fail: ./testlib.so: undefined symbol: _Z3foov 

顯然,這不好。所以我想我有兩個問題: 1)有沒有辦法讓共享對象找到它從 加載的可執行文件中的符號?2)如果不是,那麼使用插件的程序通常會如何工作,以便他們設法獲得任意代碼共享對象在其程序中運行?

回答

16

嘗試:

g++ -fPIC -rdynamic -o testexe testexe.cpp -ldl 

沒有-rdynamic(或等同的東西,如-Wl,--export-dynamic),從應用程序的符號本身將無法使用動態鏈接。

+0

是的!非常非常感謝你。 – cheshirekow 2010-09-02 02:15:05

+1

根據https://gcc.gnu.org/onlinedocs/gcc-4.8.3/gcc/Link-Options.html,使用gcc鏈接步驟的選項「-rdynamic」可以實現同樣的效果。 – 2014-10-07 15:56:41

+0

@TomBarron謝謝!我會更新我的帖子。 – 2014-10-07 17:17:31

相關問題