(一)
一般对于遵循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)
__attribute__((constructor)) void before_main()
{
printf("%s/n",__FUNCTION__);
}
__attribute__((destructor)) void after_main()
{
printf("%s/n",__FUNCTION__);
}
int main( int argc, char ** argv )
{
printf("%s/n",__FUNCTION__);
return 0;
}
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数组中添加多个函数指针。
原文链接: https://www.cnblogs.com/peterjade/archive/2011/06/12/2428490.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/27126
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!