constructor和destructor是属于通用函数属性,在如下链接中有介绍
Common Function Attributes (Using the GNU Compiler Collection (GCC))
The
constructor
attribute causes the function to be called automatically before execution entersmain ()
. Similarly, thedestructor
attribute causes the function to be called automatically aftermain ()
completes orexit ()
is called. Functions with these attributes are useful for initializing data that is used implicitly during the execution of the program.
测试代码如下:
#include <stdio.h>
__attribute__((constructor)) void before_main()
{
printf("%s\n", __func__);
}
__attribute__((destructor)) void after_main()
{
printf("%s\n",__func__);
}
int main()
{
printf("main function\n");
return 0;
}
编译执行:
# gcc test.c -o test
# ./test
before_main
main function
after_main
main函数执行之前,主要就是初始化系统相关资源:
1、设置栈指针
2、初始化static静态和global全局变量,即data段的内容
3、将未初始化部分的赋初值:数值型short,int,long等为0,bool为FALSE,指针为NULL,等等,即.bss段的内容
4、将main函数的参数,argc,argv等传递给main函数,然后才真正运行main函数