【C/C++】How to execute a particular function before main() in C?

#include<stdio.h>   

 /* Apply the constructor attribute to myStartupFun() so that it
 is executed before main() */ 

 void myStartupFun (void) __attribute__ ((constructor));

 /* Apply the destructor attribute to myCleanupFun() so that it 
 is executed after main() */

 void myCleanupFun (void) __attribute__ ((destructor));

 /* implementation of myStartupFun */ 

 void myStartupFun (void) {

 printf ("startup code before main()\n"); 

 }   

/* implementation of myCleanupFun */   

 void myCleanupFun (void) {

 printf ("cleanup code after main()\n"); 

 }   

 int main (void) {

 printf ("hello\n");

 return 0; 
 }

 

Output of the above code as below

startup code before main()
hello
cleanup code after main()

It is working as a constructor and destructor as in OOPS concept. Generally Constructor invokes when an object created; likewise destructor invokes after execution of program automatically.

__attribute__ run when a shared library is loaded during loading steps of a C program. Loading happens when a binary file is loading from secondary memory to main memory for CPU execution. In that time many shared libraries like .so files added, typically during program startup.

It uses two brackets ((, )) to distinguish them from function calls. GCC attributes are defined like that.

  __attribute__ is not a Macro or Function, it is GCC-specific syntax.

It works in C as well as C++ language.

 

ref:

http://stackoverflow.com/questions/17337744/how-to-execute-a-particular-function-before-main-in-c-and-java

https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes

你可能感兴趣的:(function)