随笔-167  评论-8  文章-0  trackbacks-0

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

 

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

   

[c-sharp] view plaincopy
  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 plaincopy
  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 plaincopy
  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 plaincopy
  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.

 


src: http://www.faqs.org/docs/Linux-HOWTO/Program-Library-HOWTO.html#INIT-AND-CLEANUP

      http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

      http://unixwiz.net/techtips/gnu-c-attributes.html

posted on 2012-02-02 16:55 老马驿站 阅读(746) 评论(0)  编辑 收藏 引用 所属分类: c++linux