您有两个选择,可以从中选择一个:
选项 1:从可执行文件中导出所有符号。这是简单的选项,只需在构建可执行文件时添加一个标志
-Wl,--export-dynamic
。这将使所有函数都可用于库调用。
选项 2:创建一个导出符号文件,并使用
-Wl,--dynamic-list=exported.txt
。这需要一些维护,但更加准确。
演示:简单的可执行文件和动态加载库。
#include <stdio.h>
#include <dlfcn.h>
void exported_callback()
{
printf("Hello from callback!\n");
}
void unexported_callback()
{
printf("Hello from unexported callback!\n");
}
typedef void (*lib_func)();
int call_library()
{
void *handle = NULL;
lib_func func = NULL;
handle = dlopen("./libprog.so", RTLD_NOW | RTLD_GLOBAL);
if (handle == NULL)
{
fprintf(stderr, "Unable to open lib: %s\n", dlerror());
return -1;
}
func = dlsym(handle, "library_function");
if (func == NULL) {
fprintf(stderr, "Unable to get symbol\n");
return -1;
}
func();
return 0;
}
int main(int argc, const char *argv[])
{
printf("Hello from main!\n");
call_library();
return 0;
}
库代码(lib.c):
#include <stdio.h>
int exported_callback();
int library_function()
{
printf("Hello from library!\n");
exported_callback();
return 0;
}
首先,构建库(此步骤无差别):
gcc -shared -fPIC lib.c -o libprog.so
现在使用导出所有符号的方式构建可执行文件:
gcc -Wl,--export-dynamic main.c -o prog.exe -ldl
运行示例:
$ ./prog.exe
Hello from main!
Hello from library!
Hello from callback!
导出的符号:
$ objdump -e prog.exe -T | grep callback
00000000004009f4 g DF .text 0000000000000015 Base exported_callback
0000000000400a09 g DF .text 0000000000000015 Base unexported_callback
现在有了导出的列表(
exported.txt
):
{
extern "C"
{
exported_callback;
};
};
构建和检查可见符号:
$ gcc -Wl,--dynamic-list=./exported.txt main.c -o prog.exe -ldl
$ objdump -e prog.exe -T | grep callback
0000000000400774 g DF .text 0000000000000015 Base exported_callback
-undefined dynamic_lookup
。在Linux上使用gcc时,这会像帖子中描述的那样神奇地工作,但我不知道为什么。 - kritzikratzi