设为首页 加入收藏

TOP

C语言中如何在main函数开始前执行函数
2014-11-23 23:33:45 来源: 作者: 【 】 浏览:1
Tags:言中 何在 main 函数 开始 执行


在gcc中,可以使用attribute关键字,声明constructor和destructor,代码如下:


[cpp]
#include

__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;
}
#include

__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中,可以使用如下方法:


[cpp]
#include

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()
#include

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数组中添加多个函数指针。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇a[i][j]与a[j][i]性能差别的原因 下一篇 error LNK2019

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: