C中main()前后执行的函数

有了GCC系列的C编译器,我们可以在main()之前和之后标记一些要执行的函数。因此,一些启动代码可以在main()启动之前执行,一些清理代码可以在main()结束之后执行。例如,在下面的程序中,myStartupFun()在main()之前调用,myCleanupFun()在main()之后调用。

null

#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()" );
}
/* implementation of myCleanupFun */
void myCleanupFun ( void )
{
printf ( "cleanup code after main()" );
}
int main ( void )
{
printf ( "hello" );
return 0;
}


输出:

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

像上面的特性一样,GCC为标准C语言添加了许多其他有趣的特性。看见 更多细节。

相关文章: 在C语言中执行main()——幕后

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享