【问题标题】:How to export specific symbol from executables in GNU/Linux如何从 GNU/Linux 中的可执行文件中导出特定符号
【发布时间】:2013-04-27 13:59:35
【问题描述】:

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

有没有办法只导出特定的函数?

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

testlib.cpp

extern void func_export(int i);

extern "C" void func_test(void)
{
  func_export(4);
}

ma​​in.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

是否可以实现只导出特定功能的需求?

【问题讨论】:

  • 你熟悉visibility options吗?
  • @LucDanton 可见性属性似乎只适用于共享库,但这里我想控制可执行符号的可见性。

标签: c++ c shared-libraries dlopen


【解决方案1】:

有没有办法只导出特定的函数?

我们需要这个功能,并在 Gold 链接器 here 中添加了 --export-dynamic-symbol 选项。

如果您使用的是 Gold,请构建一个最新版本,然后一切就绪。

如果您不使用 Gold,也许您应该使用 - 它更快,并且具有您需要的功能。

【讨论】:

  • 好的,很高兴知道。但我使用 3pp 工具链构建,所以不支持 gold
猜你喜欢
  • 2011-01-23
  • 2011-04-26
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
相关资源
最近更新 更多