__attribute__ ((constructor))与__attribute__ ((destructor))

☆ 应用程序中使用

  __attribute__ ((constructor))在main()函数之前被执行,__attribute__ ((destructor))在main()退出时执行。

  参考:http://blog.sina.com.cn/s/blog_88b60ea001017bc9.html

☆ 库中使用

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

  参考:http://blog.csdn.net/linuw/article/details/6048307

☆ 应用程序中使用

  1. test.c
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 static void before(void) __attribute__ ((constructor));
 5 
 6 static void after(void) __attribute__ ((destructor));
 7 
 8 static void before()
 9 {
10     fprintf(stderr, "In %s %d
", __func__, __LINE__);
11 }
12 
13 static void after()
14 {
15     fprintf(stderr, "In %s %d
", __func__, __LINE__);
16 }
17 
18 int main(void)
19 {        
20     printf("bengin
");
21 
22     printf("end
");
23     return 0;
24 }

2. 结果

In before 10
bengin
end
In after 15

☆ 库中使用

1. libktest.c

 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.
");
 8 }
 9 
10 void ktest_deinit(void)
11 {
12     printf("call ktest deinit.
");
13 }
14 
15 void test1()
16 {
17     printf("call test1.
");
18 }
19 
20 void test2()
21 {
22     printf("call test2.
");
23 }
24 
25 void test3()
26 {
27     printf("call test3.
");
28 }

2. calllibc.c

 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 
 8     /* below only for testing dynamic linking loader */
 9     void *handle;
10     void (*test)();
11     char *error;
12 
13     printf("++++load before++++
");
14     handle = dlopen ("./libktest.so", RTLD_LAZY);
15     if (!handle) {
16         fputs (dlerror(), stderr);
17         exit(1);
18     }
19 
20     test = dlsym(handle, "test2");
21     if ((error = dlerror()) != NULL)  {
22         fputs(error, stderr);
23         exit(1);
24     }
25 
26     (*test)();
27 
28     printf("++++unload before++++
");
29     dlclose(handle);
30 
31     return 0;
32 }

3. test_calllibc.c:

 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     printf("++++main start++++
");
 8 
 9     void test1();
10     void test2();
11     void test3();
12 
13     test1();
14     test2();
15     test3();
16     printf("++++main end++++
");
17 
18     return 0;
19 }

4. 结果

calllibc.c

++++load before++++

call ktest init.
call test2.
++++unload before++++
call ktest deinit.

test_calllibc.c

call ktest init.
++++main start++++
call test1.
call test2.
call test3.
++++main end++++
call ktest deinit.

5.  分析

dlopen加载动态库,dclose卸载动态库

编译方式,main开始之前加载,main结束之后卸载。

 

原文地址:https://www.cnblogs.com/renhl/p/4593132.html