2010-09-02 49 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

相关问题