(一)
一般对于遵循GNU 规范的c 编译器,例如gcc(3.0以及 以上版本)具有__attribute__机制,而对于非GNU的c 编译器例如vc等,也可以做到在main()之前或者之后执行其他函数,如果不能也能做到和非GNU编译器的兼容。因为__attribute__设计的非常巧妙,很容易作到和其它编译器保持兼容,也就是说,如果工作在其它的非GNU编译器上,可以很容易的忽略该属性。通过预处理就可以实现。
#ifndef __GNUC__
#define __attribute__(x) //*nothing
#endif
另外,__attribute__属性约束通常是针对函数的声明而不是定义。
(二)
example01 c-free5.0 : mingw(采用的gcc 3.4.5)
vc不支持attribute关键字,在vc中,可以使用如下方法:
- #include <stdio.h>
- int
- main( int argc, char ** argv )
- {
- printf("%s/n",__FUNCTION__);
- return 0;
- }
- int before_main()
- {
- printf("%s/n",__FUNCTION__);
- return 0;
- }
- int after_main()
- {
- printf("%s/n",__FUNCTION__);
- return 0;
- }
- typedef int func();
- #pragma data_seg(".CRT$XIU")
- static func * before[] = { before_main };
- #pragma data_seg(".CRT$XPU")
- static func * after[] = { after_main };
- #pragma data_seg()
编译执行,上述两段代码的结果均为:
before_main
main
after_main
可以在main前后调用多个函数,在gcc下使用attribute声明多个constructor、destructor,vc下在before、after数组中添加多个函数指针。