如何从GNU / Linux中的可执行文件导出特定符号
在通过::dlopen()
加载动态库时,可以通过-rdynamic
选项从可执行文件导出符号,但它会导出可执行文件的所有符号,从而导致更大的二进制文件大小。
有没有办法只导出特定的function?
例如,我有testlib.cpp和main.cpp如下:
testlib.cpp
extern void func_export(int i); extern "C" void func_test(void) { func_export(4); }
main.cpp中
#include #include 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(::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
,则导出这两个函数。
如果没有链接g++ -o main_no_rdynamic -ldl main.o
, g++ -o main_no_rdynamic -ldl main.o
,我得到运行时错误Unable to open lib: ./libtestlib.so: undefined symbol: _Z11func_exporti
是否有可能达到只导出特定function的要求?
有没有办法只导出特定的function?
我们需要此function,并在此处向Gold链接器添加了--export-dynamic-symbol
选项。
如果您正在使用Gold,请构建最新版本,您将全部完成。
如果您不使用Gold,也许您应该 – 它更快,并且具有您需要的function。