链接参数export dynamic和-rdynamic的使用


 

 

存在程序main通过dlopen使用libA中的符号:
 1 #include 
 2 #include 
 3 
 4 typedef void (*func)(void); 
 5 
 6 
 7 void test_main()
 8 {
 9     return;
10 }
11 
12 
13 int main()
14 {
15     void *handle = dlopen("./libA.so", RTLD_NOW|RTLD_GLOBAL);
16     if(NULL == handle)
17     {
18         fprintf(stderr, "%s\n", dlerror());
19         return 1;
20     }
21     func test = dlsym(handle, "test");
22 
23     (*test)();
24 
25     return 0;
26 
27 }
main.c libA的代码又反向依赖main中符号:
1 void test()
2 {
3     test_main();
4     return;
5 }
A.c 这样,gcc -g main.c -ldl 编译程序(注意这里没有链接libA),运行程序main时会报错,报错的原因就是dlopen失败,失败的原因就是:
  • ./libA.so: undefined symbol: test_main
  解决方法有两个: A、不要dlopen打开这个库,即注释掉dl过程直接调用test,此时直接大大方方的-l就可以了
  • gcc -g main_ld.c -L. -lA
B、 使用所述参数,将test_main放到程序main的动态符号表中,保证dlopen的成功:
  • gcc -rdynamic -g main.c -ldl