shared object can't find symbols in main binary, C++

拟墨画扇 提交于 2019-11-29 08:11:42

问题


I'm experimenting with making a kind of plugin architecture for a program I wrote, and at my first attempt I'm having a problem. Is it possible to access symbols from the main executable from within the shared object? I thought the following would be fine:

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;
}

Compiled with:

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

Output:

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

So obviously, it's not fine. So I guess I have two questions: 1) Is there a way to make the shared object find symbols in the executable it's loaded from 2) If not, how do programs that use plugins typically work that they manage to get code in arbitrary shared objects to run inside their programs?


回答1:


Try:

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

Without the -rdynamic (or something equivalent, like -Wl,--export-dynamic), symbols from the application itself will not be available for dynamic linking.



来源:https://stackoverflow.com/questions/3623375/shared-object-cant-find-symbols-in-main-binary-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!