通过::dlopen()
加载动态库时,可以通过-rdynamic
选项从可执行文件中导出符号,但它会导出可执行文件的所有符号,这导致更大的二进制大小。
有没有办法只导出特定的函数?
例如,我有 teSTLib.cpp 和 main.cpp 如下:
测试库.cpp
extern void func_export(int i);
extern "C" void func_test(void)
{
func_export(4);
}
main.cpp
#include <cstdio>
#include <dlfcn.h>
void func_export(int i)
{
::fprintf(stderr, "%s: %d\n", __func__, i);
}
void func_not_export(int i)
{
::fprintf(stderr, "%s: %d\n", __func__, i);
}
typedef void (*void_func)(void);
int main(void)
{
void* handle = NULL;
void_func func = NULL;
handle = ::dlopen("./libtestlib.so", RTLD_NOW | RTLD_GLOBAL);
if (handle == NULL) {
fprintf(stderr, "Unable to open lib: %s\n", ::dlerror());
return 1;
}
func = reinterpret_cast<void_func>(::dlsym(handle, "func_test"));
if (func == NULL) {
fprintf(stderr, "Unable to get symbol\n");
return 1;
}
func();
return 0;
}
编译:
g++ -fPIC -shared -o libtestlib.so testlib.cpp
g++ -c -o main.o main.cpp
我想让动态库使用func_export,但是隐藏了func_not_export。
如果与 -rdynamic 链接,
g++ -o main -ldl -rdynamic main.o
, 两个函数都被导出。
如果不与 -rdynamic 链接,
g++ -o main_no_rdynamic -ldl main.o
, 我得到了运行时错误 Unable to open lib: ./libteSTLib.so: undefined symbol: _Z11func_exporti
是否可以实现只导出特定功能的需求?
最佳答案
Is there a way to export just specific function(s)?
我们需要此功能,并向 Gold 链接器添加了 --export-dynamic-symbol
选项 here .
如果您使用的是 Gold,请构建最新版本,一切就绪。
如果您没有使用 Gold,也许您应该使用它——它速度更快,并且具有您需要的功能。
关于c++ - 如何从 GNU/Linux 中的可执行文件导出特定符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16354268/