调用栈:main() --> libsosrc.so中的soFunc--> main.out中的callBySo
#include <stdlib.h> #include <dlfcn.h> #include <stdio.h> void callBySo() { printf("callBySo\n"); } typedef int(*Func)(); int main() { const char* const so_path = "libsosrc.so"; void* handle = dlopen(so_path, RTLD_LAZY); Func func = (Func)dlsym(handle, "soFunc"); func(); dlclose(handle); return 0; }
g++ -g -ldl -rdynamic -o main.out main.cpp
链接选项-rdynamic将所有非静态函数加到动态符号表中
readelf -Ds main.out
Symbol table of `.gnu.hash' for image:
Num Buc: Value Size Type Bind Vis Ndx Name
7 0: 0000000000601048 0 NOTYPE GLOBAL DEFAULT 24 __data_start
8 0: 000000000040084d 16 FUNC GLOBAL DEFAULT 13 _Z8callBySov
......
g++ sosrc.cpp -fPIC -shared -g -o libsosrc.so
#include<stdio.h> #ifdef __cplusplus extern "C" { #endif void soFunc(); #ifdef __cplusplus } #endif extern void callBySo(); void soFunc() { printf("soFunc\n"); callBySo(); }