【转】【C/C++】How to execute a particular function before main() in C?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了【转】【C/C++】How to execute a particular function before main() in C?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1676字,纯文字阅读大概需要3分钟。
内容图文
![【转】【C/C++】How to execute a particular function before main() in C?](/upload/InfoBanner/zyjiaocheng/1110/61477d35b8104ea48e0e10f928b2dd4f.jpg)
#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"); return0; }
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
原文:http://www.cnblogs.com/xjsxjtu/p/4674096.html
内容总结
以上是互联网集市为您收集整理的【转】【C/C++】How to execute a particular function before main() in C?全部内容,希望文章能够帮你解决【转】【C/C++】How to execute a particular function before main() in C?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。