GNU C的一大特色就是__attribute__机制,__attribute__可以设置函数属性、变量属性和类型属性。
其位置约束放在申明的尾部“;”之前;书写特征为前后两个下划线,后面紧跟一对原括弧,里面是相应的__attribute__参数。
__attribute__ constructor/destructor 若函数被设定为constructor属性,则该函数会在 main()函数执行之前被自动的执行。类似的,若函数被设定为destructor属性,则该函数会在main()函数执行之后或者exit()被调用后被自动的执行。拥有此类属性的函数经常隐式的用在程序的初始化数据方面。
代码如下:
#include <stdio.h>
__attribute((constructor)) void before_main()
{
printf("%s\n", __FUNCTION__);
}
__attribute((destructor)) void after_main()
{
printf("%s\n", __FUNCTION__);
}
int main()
{
char* str1 = "IPHOST";
char* str2 = "IPOE";
int ret = strcmp(str1, str2);
printf("%d\n", ret);
}
输出如下:
before_main
-7
after_main