gcc下__attribute__ ((constructor))和__attribute__ ((destructor))的使用

 

gcc下__attribute__ ((constructor))和__attribute__ ((destructor))的使用

__attribute__ ((constructor))指定的函数在共享库loading的时候调用,__attribute__ ((destructor))指定的函数在共享库unloading的时候调用。

 

1. 编写源码文件ktest.c如下.

   

[c-sharp]  view plain copy
  1. #include <stdio.h>  
  2. __attribute__ ((constructor)) static void ktest_init(void);  
  3. __attribute__ ((destructor)) static void ktest_deinit(void);  
  4.   
  5. void ktest_init(void)  
  6. {  
  7.     printf("call ktest init./n");  
  8. }  
  9.   
  10. void ktest_deinit(void)  
  11. {  
  12.     printf("call ktest deinit./n");  
  13. }  
  14.   
  15. void test1()  
  16. {  
  17.     printf("call test1./n");  
  18. }  
  19.   
  20. void test2()  
  21. {  
  22.     printf("call test2./n");  
  23. }  
  24.   
  25. void test3()  
  26. {  
  27.     printf("call test3./n");  
  28. }  

 

2. 编译为共享库libktest.so

   

[c-sharp]  view plain copy
  1. gcc -fPIC -c ktest.c   ### produce ktest.o.  
  2. gcc -shared -o libktest.so ktest.o ### produce libktes.so  

 

3. 编写库调用文件calllib.c

   

[c-sharp]  view plain copy
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <dlfcn.h> /* dlopen, dlsym, dlclose */  
  4.   
  5. int main(int argc, char **argv)  
  6. {  
  7.     test1();  
  8.     test2();  
  9.     test3();  
  10.   
  11.     /* below only for testing dynamic linking loader */  
  12.     void *handle;  
  13.     void (*test)();  
  14.     char *error;  
  15.   
  16.     handle = dlopen ("/path_to_lib/libktest.so", RTLD_LAZY);  
  17.     if (!handle) {  
  18.         fputs (dlerror(), stderr);  
  19.         exit(1);  
  20.     }  
  21.   
  22.     test = dlsym(handle, "test2");  
  23.     if ((error = dlerror()) != NULL)  {  
  24.         fputs(error, stderr);  
  25.         exit(1);  
  26.     }  
  27.   
  28.     (*test)();  
  29.     dlclose(handle);  
  30.   
  31.     return 0;  
  32. }  

 

4. 编译calllib运行, 将可以看到ktest_init() 和ktest_deinit()已被调用.

[c-sharp]  view plain copy
  1. gcc calllib.c -o calllib -ldl -L./ -lktest  ### produce calllib  
  2.   
  3. export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH && ./calllib  

call ktest init.
call test1.
call test2.
call test3.
call test2.
call ktest deinit.

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值