



In GCC C compiler, we have nice feature to execute the certain function before and after main( ). So some startup code can be executed before main( ) starts, and some cleanup code can be executed after main() ends. For example, in the following program, StartupFunction( ) is called before main( ) and CleanupFunction( ) is called after main( ).

#include<stdio.h> /* Apply the constructor attribute to StartupFunction() so that it is executed before main() */ void StartupFunction(void) __attribute__ ((constructor)); /* Apply the destructor attribute to CleanupFunction() so that it is executed after main() */ void CleanupFunction(void) __attribute__ ((destructor)); /* implementation of StartupFunction*/ void StartupFunction(void) { printf ("startup code before main()

"); } /* implementation of CleanupFunctiom */ void CleanupFunction(void) { printf ("cleanup code after main()

"); } int main (void) { printf ("hello

"); return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include<stdio.h> /* Apply the constructor attribute to StartupFunction() so that it is executed before main() */ void StartupFunction ( void ) __attribute__ ( ( constructor ) ) ; /* Apply the destructor attribute to CleanupFunction() so that it is executed after main() */ void CleanupFunction ( void ) __attribute__ ( ( destructor ) ) ; /* implementation of StartupFunction*/ void StartupFunction ( void ) { printf ( "startup code before main()

" ) ; } /* implementation of CleanupFunctiom */ void CleanupFunction ( void ) { printf ( "cleanup code after main()

" ) ; } int main ( void ) { printf ( "hello

" ) ; return 0 ; }

Output