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

标签 c++ c shared-libraries dlopen

通过::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/

相关文章:

c - 使用 g_rename 函数编译 GTK+ 应用程序时出错

c - opengl中的半圆柱体/封闭圆柱体

c - 即使文件已经打开以进行独占访问,如何获取文件大小?

c++ - 仅检查共享库中的内存问题(例如 Apache 模块)

c++ - 用于插入的高效数据结构

c++ - 无法绑定(bind)可变 lambda

创建数组时 C++ 内存泄漏

c++ - 加入 16 位有符号整数的 MSB 和 LSB(二进制补码)

python - 从单个 .cpp 构建共享对象

linux - 强制 GCC 静态链接,例如pthreads(而不是动态链接)