今天和同事讨论babeltrace的时候,一直找不到新format库的入口,后来仔细查找了一下已有的格式转换ctf-text的注册函数定义:void __attribute__((constructor)) ctf_text_init(void),发现了这个有趣的使用方法: __attribute__((constructor))这个东东相似于C++的构造函数,在main()前被调用. 相似的还有__attribute__((destructor))。 下面是一个网上搜索到的一个测试例子:ios
__attribute__((constructor))
__attribute__((destructor))babel
$ gcc test.c -o test
$ ./test
before main
in main
after main函数
根据上面的代码以及输出结果,咱们能够猜到__attribute__((constructor))表示这段代码将在main函数前调用,就像在C++里面的全局变量类的构造同样.测试
说到C++里面的全局类对象的构造,咱们不由要问全局类对象的构造跟__attribute__((constructor))以及destructor谁在前谁在后呢?spa
$ make test2orm
$ ./test2对象
AAA construct
Before Main
in main
AAA destructor
After Mainit
能够看到全局类的构造过程发生在before_main()函数前面,而析构也发生在after_main()前面.io