您的位置:首页 > 其它

__attribute__

2012-05-08 00:00 162 查看
今天和同事讨论babeltrace的时候,一直找不到新format库的入口,后来仔细查找了一下已有的格式转换ctf-text的注册函数定义:void __attribute__((constructor)) ctf_text_init(void),发现了这个有趣的使用方法: __attribute__((constructor))这个东东类似于C++的构造函数,在main()前被调用. 类似的还有__attribute__((destructor))。 下面是一个网上搜索到的一个测试例子:

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

#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谁在前谁在后呢?

#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()前面.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息