cc允许为函数设置__attribute__ ((constructor))和__attribute__ ((destructor))两种属性,顾名思义,就是将被修饰的函数作为构造函数或析构函数。程序员可以通过类似下面的方式为函数设置这些属性:
带有(constructor)属性的函数将在main()函数之前被执行,而带有(destructor)属性的函数将在main()退出时执行。
下面给出一个简单的例子:
#include <stdio.h>
#include <stdlib.h>
void __attribute__((constructor)) con_func()
{
printf("befor main: constructor is called..\n");
}
void __attribute__((destructor)) des_func()
{
printf("after main: destructor is called..\n");
}
int main()
{
printf("main func..\n");
return 0;
}
编译并运行程序:
[root@ubuntu workshop]# gcc constructor.c -o constructor
[root@ubuntu workshop]# ./constructor
befor main: constructor is called.
main func...
after main: destructor is called..