函数属性 __attribute__ ((constructor))和__attribute__ ((destructor))

函数属性constructor和destructor, 构造函数初始化属性init_priority

函数属性功能

__attribute__ ((constructor))会使函数在main()函数之前被执行

__attribute__ ((destructor))会使函数在main()退出后执行

功能范围

函数属性__attribute__((constructor))和__attribute__((destructor))在可执行文件或者库文件里都可以生效

与全局变量比较

全局变量对象的构造函数可以通过__attribute__((init_priority())和__attribute__((constructor))标志的函数的调整执行的优先顺序

可执行文件的函数调用

例子如下:

函数属性 __attribute__ ((constructor))和__attribute__ ((destructor))

 

输出结果:

函数属性 __attribute__ ((constructor))和__attribute__ ((destructor))

 

这里beforemain 和构造函数不能使用std::cout, 只能使用printf, 因为cout 需要全局变量初始化,但是beforemain和全局构造函数比他执行的早。