吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → 在 C 中 main() 之前和之后执行的函数

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

来源:网络 | 更新时间:2022-01-14 20:24:32
使用 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 语言添加了许多其他有趣的特性。

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com