GCC设置函数属性为constructor和destructor

本文介绍了GCC编译器如何使用__attribute__((constructor))和__attribute__((destructor))属性来定义在main()函数前后执行的构造和析构函数。通过示例代码展示了构造函数在main()函数开始前调用,而析构函数在main()函数结束后调用。

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

cc允许为函数设置__attribute__ ((constructor))和__attribute__ ((destructor))两种属性,顾名思义,就是将被修饰的函数作为构造函数或析构函数。程序员可以通过类似下面的方式为函数设置这些属性:

 

带有(constructor)属性的函数将在main()函数之前被执行,而带有(destructor)属性的函数将在main()退出时执行。

下面给出一个简单的例子:

#include <stdio.h>
#include <stdlib.h>
void __attribute__((constructor)) con_func()
{
    printf("befor main: constructor is called..\n");
}
void __attribute__((destructor)) des_func()
{
    printf("after main: destructor is called..\n");
}
int main()
{
    printf("main func..\n");
    return 0;
}

 

编译并运行程序:

[root@ubuntu workshop]# gcc constructor.c -o constructor
[root@ubuntu workshop]# ./constructor 
befor main: constructor is called.
main func...
after main: destructor is called..

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值