使用 GCC 系列的 C 编译器,我们可以标记一些函数在 main() 之前和之后执行。所以一些启动代码可以在main()开始之前执行,一些清理代码可以在main()结束之后执行。例如,在以下程序中,myStartupFun() 在 main() 之前调用,myCleanupFun() 在 main() 之后调用。
输出:
#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 ("hellon");
return 0;
}
startup code before main() hello cleanup code after main()与上述特性一样,GCC 还为标准 C 语言添加了许多其他有趣的特性。