【问题标题】:dlopen cant find demangled symbolsdlopen 找不到解散的符号
【发布时间】:2014-10-20 23:58:47
【问题描述】:

我正在尝试允许共享库从它被加载到的进程中调用一个函数。该库是用 C 编写的,即 C++ 中的“内核”。

kernel.cpp:

#include <stdio.h>
#include <dlfcn.h>

typedef void(*func_t)();

extern "C" {
        void test();
}

int main() {
        char *error;
        void *handle = dlopen("./library.so", RTLD_LAZY);
        if((error = dlerror()) != NULL) {
                fprintf(stderr, "%s\n", error);
                return 1;
        }
        func_t init = (func_t)dlsym(handle, "init");
        if((error = dlerror()) != NULL) {
                fprintf(stderr, "%s\n", error);
                return 1;
        }
        init();

        return 0;
}

void test() {
        fprintf(stderr, "test() called.\n");
}

图书馆.c:

#include <stdio.h>

void test();

void init() {
        fprintf(stderr, "init() called.\n");
        test();
}

制作文件:

all:
        g++ -ldl kernel.cpp -o kernel
        gcc -fpic -shared library.c -o library.so
        ./kernel

objdump -x 内核

SYMBOL TABLE: 
... 
000000000040088b g     F .text  0000000000000024    test

运行程序,我得到以下输出:

init() called.
./kernel: symbol lookup error: ./library.so: undefined symbol: test

如果我将 dlopen 更改为使用 RTLD_NOW,我会得到:

./library.so: undefined symbol: test

为什么图书馆很难找到那个符号,而它显然没有被破坏,就坐在那里?

【问题讨论】:

  • 当你声明它时你说extern "C",但是当你定义它时你没有。

标签: c++ c linker dlopen


【解决方案1】:

默认情况下不导出可执行文件的符号。

您需要 -export-dynamic 链接器标志来链接可执行文件:

g++ -ldl -Wl,-export-dynamic kernel.C -o kernel

引用 ld 手册页,它描述了您的确切场景:

If you use "dlopen" to load a dynamic object which needs to refer
back to the symbols defined by the program, rather than some other
dynamic object, then you will probably need to use this option when
linking the program itself.

【讨论】:

  • 您可以只使用g++ -Wall -rdynamic kernel.C -o kernel -ldl,因为-rdynamic-Wl,-export-dynamic 相同
  • 这仍然没有解决任何问题,但这次我得到 library.so: undefined symbol: init and filename is not kernel.C its kernel.cpp
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多