main函数开始前执行函数

来源:互联网 发布:太原医院挂号软件 编辑:程序博客网 时间:2024/05/01 08:09
C语言中怎么在main函数开始前执行函数呢?下面小编就大家详细的介绍一下。需要的朋友可以过来参考下,希望对大家有所帮助

在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

可以在main前后调用多个函数,在gcc下使用attribute声明多个constructor、destructor,vc下在before、after数组中添加多个函数指针。

0 0
原创粉丝点击