代码之家  ›  专栏  ›  技术社区  ›  cheshirekow

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

  •  10
  • cheshirekow  · 技术社区  · 14 年前

    测试库.cpp:

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

    测试工具.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) 如果不是的话,那么使用插件的程序通常是如何工作的,它们可以让任意共享对象中的代码在程序中运行?

    1 回复  |  直到 14 年前
        1
  •  19
  •   C. K. Young    10 年前

    尝试:

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

    -rdynamic (或者类似的东西,比如 -Wl,--export-dynamic