3

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?

Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
Mine
  • 4,123
  • 1
  • 25
  • 46
  • 2
    Are you familiar with [visibility options](http://gcc.gnu.org/wiki/Visibility)? – Luc Danton May 03 '13 at 08:11
  • @LucDanton The visibility attribute seems only works on the shared library, but here I want to control the visibility of the executable symbols. – Mine May 03 '13 at 08:24

1 Answers1

4

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.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
  • OK, it's good to know. But I'm using 3pp toolchain to build so `gold` is not supported. – Mine May 09 '13 at 05:11