通过一个简单的例子介绍一下gcc的__attribute__ ((constructor))属性的作用。gcc允许为函数设置__attribute__ ((constructor))和__attribute__ ((destructor))两种属性,顾名思义,就是将被修饰的函数作为构造函数或析构函数。程序员可以通过类似下面的方式为函数设置这些属性:
void funcBeforeMain() __attribute__ ((constructor));
void funcAfterMain() __attribute__ ((destructor));
也可以放在函数名之前:
void __attribute__ ((constructor)) funcBeforeMain();
void __attribute__ ((destructor)) funcAfterMain();
带有(constructor)属性的函数将在main()函数之前被执行,而带有(destructor)属性的函数将在main()退出时执行。
下面给出一个简单的例子:
1 #include <stdio.h> 2 3 void __attribute__((constructor)) funcBeforeMain() 4 { 5 printf("%s...\n", __FUNCTION__); 6 } 7 8 void __attribute__((destructor)) funcAfterMain() 9 { 10 printf("%s...\n", __FUNCTION__); 11 } 12 13 int main() 14 { 15 printf("main...\n"); 16 return 0; 17 }
运行结果:
funcBeforeMain...
main...
funcAfterMain...
为什么有这么神奇的函数呢?它是怎么实现的呢?
通过翻看GNU的link文档,我找到了答案:
在GNU link中,也就是你的系统中的XX.S文件,找到了详细的答案,
当使用a.out文件来链接程序时,链接器使用一个与众不同的关键字construct 来支持C++里面的全局constructors 和 destructors,当链接对象不支持任意剖分时,链接器可以通过名字来自动识别构造器和解析器。
link文件中的构造器格式如下:
1 __CTOR_LIST__ = .; 2 LONG((__CTOR_END__ - __CTOR_LIST__) / 4 - 2) 3 *(.ctors) 4 LONG(0) 5 __CTOR_END__ = .; 6 __DTOR_LIST__ = .; 7 LONG((__DTOR_END__ - __DTOR_LIST__) / 4 - 2) 8 *(.dtors) 9 LONG(0) 10 __DTOR_END__ = .;