// first.cpp
#include <stdio.h>
void print_message(){
printf("the first function\n");
}
// second.cpp
#include <stdio.h>
void print_message(){
printf("the second function\n");
}
#include <stdio.h>
#include <dlfcn.h>
#include <errno.h>
void(*f)();
void load_func() __attribute__((constructor));
void load_func(){
f = (void(*)())dlsym(RTLD_NEXT,"print_message");
char *error_str;
error_str = dlerror();
if (error_str != NULL) {
printf("%s\n", error_str);
}
printf("load func first f=%p\n",f);
}
void print_message(){
printf("the main function\n");
f();
}
int main(){
f();
return 0;
}
首先把前两个 程序编译成共享库
g++ -fpic --shared first.cpp -o libfirst.so
g++ -fpic --shared second.cpp -o libsecond.so
然后链接,这两个库编译main文件
g++ -g -o test main.cpp -lfirst -lsecond -ldl -L./
然后运行这个test程序,就会发现段错误
./test: undefined symbol: print_message
load func first f=(nil)
段错误
显然是由于print_message没有找到,那就看看libfirst.so和libsecond.so的符号表
// nm libfirst.s