码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-07-24 20:12:43      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

#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

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

标签:

原文地址:http://www.cnblogs.com/xjsxjtu/p/4674096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!