共享对象无法在主二进制,C ++中找到符号

问题描述:

我正在尝试为我编写的程序制作一种插件架构,在我第一次尝试时遇到问题。是否可以从共享对象中的主可执行文件访问符号?我认为以下情况会很好:

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:

testlib.cpp:

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

testexe.cpp:

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)如果不是,如何使用插件的程序通常工作,他们

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?

尝试:

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

没有 -rdynamic (或类似 -Wl, - export-dynamic ),应用程序本身的符号将无法用于动态链接。

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