How to export specific symbol from executables in GNU/Linux

雨燕双飞 提交于 2019-12-22 12:15:09

问题


While loading dynamic libraries by ::dlopen(), exporting symbols from executables can be done by -rdynamic option, but it exports all the symbols of the executable, which results in bigger binary size.

Is there a way to export just specific function(s)?

For example, I have testlib.cpp and main.cpp as below:

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: %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;
}

Compile:

g++ -fPIC -shared -o libtestlib.so testlib.cpp
g++ -c -o main.o main.cpp

I want func_export to be used by the dynamic library, but hide the func_not_export.

If link with -rdynamic, g++ -o main -ldl -rdynamic main.o , both functions are exported.

If not link with -rdynamic, g++ -o main_no_rdynamic -ldl main.o , I got runtime error Unable to open lib: ./libtestlib.so: undefined symbol: _Z11func_exporti

Is it possible to achieve the requirement that only export the specific function?


回答1:


Is there a way to export just specific function(s)?

We needed this functionality, and added --export-dynamic-symbol option to the Gold linker here.

If you are using Gold, build a recent version and you'll be all set.

If you are not using Gold, perhaps you should -- it's much faster, and has the functionality you need.



来源:https://stackoverflow.com/questions/16354268/how-to-export-specific-symbol-from-executables-in-gnu-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!