如何从GNU/Linux的可执行文件中导出特定的符号

How to export specific symbol from executables in GNU/Linux

本文关键字:符号 可执行文件 GNU Linux      更新时间:2023-10-16

通过::dlopen()加载动态库时,可以通过-rdynamic选项导出可执行文件中的符号,但它会导出可执行文件中的所有符号,从而导致二进制文件的大小变大。

有一种方法来导出只是特定的功能(s)?

例如,我有testlib.cpp和main.cpp如下:

testlib.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: %dn", __func__, i);
}
void func_not_export(int i)
{
  ::fprintf(stderr, "%s: %dn", __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: %sn", ::dlerror());
    return 1;
  }
  func = reinterpret_cast<void_func>(::dlsym(handle, "func_test"));
  if (func == NULL) {
    fprintf(stderr, "Unable to get symboln");
    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

是否有可能实现只导出特定功能的要求?

有一种方法来导出只是特定的功能(s)?

我们需要这个功能,并在这里为黄金链接器添加了--export-dynamic-symbol选项。

如果你使用的是Gold,构建一个最新的版本,你就会一切就绪。

如果你没有使用Gold,也许你应该使用它——它要快得多,并且有你需要的功能。

相关文章: