C语言 设置在main 之前运行的函数

本文介绍了如何使用GCC的__attribute__((constructor))和__attribute__((destructor))特性来指定函数在main函数之前或之后执行的方法,并提供了两种不同平台上的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们知道 C++的对象全局对象的构造函数会在main之前运行,例如windows MFC里面,在WinMain 函数前声明了一个theApp对象,其构造函数就在WinMain之前运行,其实在C语言中很早就有了,在gcc中可以使用__attribute__关键字指定如下(注意,这个和诸如on exit之类可不一样,这个是编译器编译的时候就决定了的)

#include <stdio.h>  
void before() __attribute__((constructor));  
void after() __attribute__((destructor));  
  
void before()  
{  
    printf("this is function %s/n", __func__);  
    return;  
}  
  
void after()  
{  
    printf("this is function %s/n", __func__);  
    return;  
}  
  
int main(int argc, char **argv)  
{  
    printf("this is function %s/n", __func__);  
    return 0;  
}  
指定了函数在main之前或之后运行。
当然也可以指派多个,而且在申明时 
void before() __attribute__((constructor));
void __attribute__((constructor)) before();
__attribute__((constructor)) void before();

这3种都是对的,__attribute__(())写法比较随意,当一般推荐放在后面,当然定义函数体的时候 __attribute__(()) 不能放在后面,推荐定义函数的时候一般不要使用,这就是为什么推荐第一种的原因,__attribute__属性列表的用法还有还多,内存对齐,函数格式, 等等等等就不一一列举了。man gcc 查找下 __attribute__可以发现这些,另标准库和Linux内核里面也有不少。

也可以一次指定多个属性 如下:

void func(void) __attribute__((constructor destructor));

attribute 是gcc、 g++的关键字,VC是不能用这个的,

如果您是在Windows下你可以指定设定数据段来做,以实现同样功能,如下:

#include <stdio.h>  
   
int main(int argc, char ** argv)  
{  
    printf("%s\n", "main");  
    return 0;  
}  
   
int before()  
{  
    printf("%s\n", "before");  
    return 0;  
}  
   
int after()  
{  
    printf("%s\n", "after");  
    return 0;  
}  
  
typedef int func();  
  
#pragma data_seg(".CRT$XIU")  
static func *before_function_array[] = { before };  
  
#pragma data_seg(".CRT$XPU")  
static func *after_function_array[] = { after };  
#pragma data_seg() 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值