问题
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