Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在GNU/Linux中从可执行文件导出特定符号_C++_C_Shared Libraries_Dlopen - Fatal编程技术网

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

C++ 如何在GNU/Linux中从可执行文件导出特定符号,c++,c,shared-libraries,dlopen,C++,C,Shared Libraries,Dlopen,通过::dlopen()加载动态库时,可以通过-rdynamic选项从可执行文件导出符号,但它会导出可执行文件的所有符号,这会导致较大的二进制大小 是否有方法仅导出特定功能 例如,我有testlib.cpp和main.cpp,如下所示: testlib.cpp extern void func_export(int i); extern "C" void func_test(void) { func_export(4); } #include <cstdio> #includ

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

是否有方法仅导出特定功能

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

testlib.cpp

extern void func_export(int i);

extern "C" void func_test(void)
{
  func_export(4);
}
#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;
}
main.cpp

extern void func_export(int i);

extern "C" void func_test(void)
{
  func_export(4);
}
#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;
}
我希望动态库使用func_导出,但隐藏func_not_导出

如果链接到-rdynamic,
g++-o main-ldl-rdynamic main.o
,这两个函数都将导出

如果未与-rdynamic链接,
g++-o main\u no\r动态-ldl main.o
,我遇到运行时错误
无法打开库:./libtestlib.so:未定义的符号:_Z11func\u exporti

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

是否有方法仅导出特定功能

我们需要此功能,并向黄金链接器添加了
--export dynamic symbol
选项

如果您使用的是Gold,那么构建一个最新版本,您就可以完成所有设置


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

您熟悉吗?@LucDanton可见性属性似乎只适用于共享库,但这里我想控制可执行符号的可见性。好的,很高兴知道。但我使用3pp工具链来构建,因此不支持
gold