__attribute__((constructor)) 与__attribute__((destructor)) 的用法

        __attribute__((constructor)) 与 __attribute__((destructor)) 是 GCC 中用来修饰函数的,constructor 可以使被修饰的函数在 main() 执行前被调用,destructor 可以使被修饰的函数在 main() 执行结束或 exit() 调用结束后被执行。

__attribute__((constructor)) void constructor_func() {
    // ...
}

__attribute__((destructor)) void destructor_func() {
    // ...
}

        一个程序中可以存在多个 constructor 和 destructor,使用优先级区分执行顺序,数字越小表示优先级越高(100 以内的优先级为保留数字不能设置)。constructor 中优先级越高越靠前执行,destructor 中优先级越高越靠后执行。不加优先级参数相当于最低优先级。

__attribute__((constructor(priority)))) void constructor_func() {
    // ...
}

__attribute__((destructor(priority)))) void destructor_func() {
    // ...
}

        与 atexit() 同时使用时,atexit() 定义的函数会在 destructor 之前执行,如下例子:

#include <stdio.h>
#include <stdlib.h>

void atexit_func (void)
{
    printf("atexit_func\n");
}

__attribute__((constructor)) void constructor_func (void)
{
    printf("constructor_func\n");
}

__attribute__((constructor(105))) void constructor_func_105 (void)
{
    printf("constructor_func 105\n");
}

__attribute__((constructor(106))) void constructor_func_106 (void)
{
    printf("constructor_func 106\n");
}

__attribute__((constructor(107))) void constructor_func_107 (void)
{
    printf("constructor_func 107\n");
}
__attribute__((constructor(1007))) void constructor_func_1007 (void)
{
    printf("constructor_func 1007\n");
}

__attribute__((destructor)) void destructor_func (void)
{
    printf("destructor_func\n");
}

__attribute__((destructor(105))) void destructor_func_105 (void)
{
    printf("destructor_func 105\n");
}

__attribute__((destructor(106))) void destructor_func_106 (void)
{
    printf("destructor_func 106\n");
}

__attribute__((destructor(107))) void destructor_func_107 (void)
{
    printf("destructor_func 107\n");
}

__attribute__((destructor(1007))) void destructor_func_1007 (void)
{
    printf("destructor_func 1007\n");
}

int main (int argc, char *argv[])
{

    atexit(atexit_func);

    return (0);
}

执行结果:

 

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

stone8761

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值