在main函数前后执行的函数之 C语言

在gcc中,可以使用attribute关键字,声明constructor和destructor,来指定了函数在main之前或之后运行,代码如下:

 1 #include <stdio.h>
 2 
 3 __attribute((constructor)) void before_main()
 4 {
 5     printf("%s/n",__FUNCTION__);
 6 }
 7 
 8 __attribute((destructor)) void after_main()
 9 {
10     printf("%s/n",__FUNCTION__);
11 }
12 
13 int main( int argc, char ** argv )
14 {
15     printf("%s/n",__FUNCTION__);
16     return 0;
17 }

当然也可以指派多个,而且在申明时 
void before() __attribute__((constructor));
void __attribute__((constructor)) before();
__attribute__((constructor)) void before();

这3种都是对的,__attribute__(())写法比较随意,当一般推荐放在后面,当然定义函数体的时候 __attribute__(()) 不能放在后面,推荐定义函数的时候一般不要使用,这就是为什么推荐第一种的原因,__attribute__属性列表的用法还有还多,内存对齐,函数格 式, 等等等等就不一一列举了。man gcc 查找下 __attribute__可以发现这些,另标准库和Linux内核里面也有不少。

也可以一次指定多个属性 如下:

1 void func(void) __attribute__((constructor destructor));  

在Windows的VC++中可以指定设定数据段来做,以实现同样功能,如下:

 1 #include <stdio.h>
 2  
 3 int main(int argc, char ** argv)
 4 {
 5     printf("%s
", "main");
 6     return 0;
 7 }
 8  
 9 int before()
10 {
11     printf("%s
", "before");
12     return 0;
13 }
14  
15 int after()
16 {
17     printf("%s
", "after");
18     return 0;
19 }
20 
21 typedef int func();
22 
23 #pragma data_seg(".CRT$XIU")
24 static func *before_function_array[] = { before };
25 
26 #pragma data_seg(".CRT$XPU")
27 static func *after_function_array[] = { after };
28 
29 #pragma data_seg()

attribute还有个应用, 就是增加函数别名(下面那个就不能是main了,要不就重复定义了):

# include <stdio.h>
int main(int argc, char **argv) __attribute__((alias("LinuxMain")));

int LinuxMain(int argc, char **argv)
{
    printf("%s
", __func__);
    return 0;
}

int main123(int argc, char **argv)
{
    printf("%s
", __func__);
    return 0;
}
原文地址:https://www.cnblogs.com/marvin-notes/p/4432179.html