GCC __attribute__((constructor)|(destructor))

在阅读TGTD的代码时发现了一个非常诡异的问题,声明了一个空的全局数组,在使用的时候却发现数组非空,在main()入口时数组已经非空.数组时在什么地方被赋值了呢?最后发现__attribute__这个东东在起作用,类似于全局变量类的构造函数在main()前被调用.

__attribute__((constructor))
__attribute__((destructor))

/* test.c */

#include<stdio.h>
__attribute__((constructor)) void before_main()
{
   printf("before main/n");
}

__attribute__((destructor)) void after_main()
{
   printf("after main/n");
}

int main()
{
   printf("in main/n");
   return 0;
}

$ gcc test.c -o test
$ ./test
before main
in main
after main

根据上面的代码以及输出结果,我们可以猜到__attribute__((constructor))表示这段代码将在main函数前调用,就像在C++里面的全局变量类的构造一样.

说到C++里面的全局类对象的构造,我们不禁要问全局类对象的构造跟__attribute__((constructor))以及destructor谁在前谁在后呢?

/*test2.cpp*/

#include<iostream>
using namespace std;
__attribute__((constructor)) void before_main()
{
    cout<<"Before Main"<<endl;
}
__attribute__((destructor)) void after_main()
{
    cout<<"After Main"<<endl;
}
class AAA{
    public:
    AAA(){
        cout<<"AAA construct"<<endl;
    }   
    ~AAA(){
        cout<<"AAA destructor" <<endl;
    }   
};
AAA A;
int main()
{
    cout<<"in main"<<endl;
    return 0;
}

$ make test2

$ ./test2

AAA construct
Before Main
in main
AAA destructor
After Main

可以看到全局类的构造过程发生在before_main()函数前面,而析构也发生在after_main()前面.

  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值