☆ Use in Applications
__attribute__ ((constructor)) is executed before the main () function, and __attribute__ ((destructor)) executes when main () exits.
Reference: http://blog.sina.com.cn/s/blog_88b60ea001017bc9.html
☆ Use in Library
The function specified by __attribute__ ((constructor)) is called when the shared library loading, and the function specified by __attribute__ ((destructor)) is called when the shared library is unloading.
Reference: http://blog.csdn.net/linuw/article/details/6048307
☆ Use in Applications
- TEST.c
1#include <stdio.h>2#include <stdlib.h>3 4 Static voidBefore (void) __attribute__ ((constructor));5 6 Static voidAftervoid) __attribute__ ((destructor));7 8 Static voidbefore ()9 {Tenfprintf (stderr,"In %s%d\n", __func__, __line__); One } A - Static voidAfter () - { thefprintf (stderr,"In %s%d\n", __func__, __line__); - } - - intMainvoid) + { -printf"bengin\n"); + Aprintf"end\n"); at return 0; -}
2. Results
Ten
☆ Use in Library
1. libktest.c
1#include <stdio.h>2__attribute__ ((constructor))Static voidKtest_init (void);3__attribute__ ((destructor))Static voidKtest_deinit (void);4 5 voidKtest_init (void)6 {7printf"Call ktest init.\n");8 }9 Ten voidKtest_deinit (void) One { Aprintf"Call ktest deinit.\n"); - } - the voidtest1 () - { -printf"Call test1.\n"); - } + - voidtest2 () + { Aprintf"Call test2.\n"); at } - - voidtest3 () - { -printf"Call test3.\n"); -}
2. calllibc.c
1#include <stdlib.h>2#include <stdio.h>3#include <dlfcn.h>/*Dlopen, Dlsym, Dlclose*/4 5 intMainintargcChar**argv)6 {7 8 /*below for testing dynamic linking loader*/9 void*handle;Ten void(*test) (); One Char*error; A -printf"++++load before++++\n"); -Handle = Dlopen ("./libktest.so", rtld_lazy); the if(!handle) { - fputs (Dlerror (), stderr); -Exit1); - } + -Test = Dlsym (handle,"test2"); + if(Error = Dlerror ())! =NULL) { A fputs (Error, stderr); atExit1); - } - -(*test) (); - -printf"++++unload before++++\n"); in Dlclose (handle); - to return 0; +}
3. TEST_CALLLIBC.C:
1#include <stdlib.h>2#include <stdio.h>3#include <dlfcn.h>/*Dlopen, Dlsym, Dlclose*/4 5 intMainintargcChar**argv)6 {7printf"++++main start++++\n");8 9 voidtest1 ();Ten voidtest2 (); One voidtest3 (); A - test1 (); - test2 (); the test3 (); -printf"++++main end++++\n"); - - return 0; +}
4. Results
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. Analysis
Dlopen load Dynamic Library, dclose unload dynamic Library
The compile mode, main starts before loading, and main ends after unloading.
__attribute__ ((constructor)) and __attribute__ ((destructor))