您的位置:首页 > 大数据 > 人工智能

语言中如何在main函数开始前执行函数

2015-07-28 19:17 656 查看
 在gcc中,可以使用attribute关键字,声明constructor和destructor,代码如下:

#include <stdio.h>  

  

__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

 (vc中可能不支持__FUNCTION__来获得函数名,你可以用另外的方式来获取,比如在befor_main()函数中printf("befor_main()\n");来模拟__FUNCTION__的功能!嘿嘿)

  可以在main前后调用多个函数,在gcc下使用attribute声明多个constructor、destructor,vc下在before、after数组中添加多个函数指针。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: