GCC的__attribute__ ((constructor))和__attribute__ ((destructor))

时间:2023-03-09 07:58:52
GCC的__attribute__ ((constructor))和__attribute__ ((destructor))

通过一个简单的例子介绍一下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()退出时执行。
下面给出一个简单的例子:
 #include <stdio.h>

 void __attribute__((constructor)) funcBeforeMain()
{
printf("%s...\n", __FUNCTION__);
} void __attribute__((destructor)) funcAfterMain()
{
printf("%s...\n", __FUNCTION__);
} int main()
{
printf("main...\n");
return ;
}

运行结果:

funcBeforeMain...
main...
funcAfterMain...

  为什么有这么神奇的函数呢?它是怎么实现的呢?

  通过翻看GNU的link文档,我找到了答案:

在GNU link中,也就是你的系统中的XX.S文件,找到了详细的答案,

当使用a.out文件来链接程序时,链接器使用一个与众不同的关键字construct 来支持C++里面的全局constructors 和 destructors,当链接对象不支持任意剖分时,链接器可以通过名字来自动识别构造器和解析器。

link文件中的构造器格式如下:

       __CTOR_LIST__ = .;
LONG((__CTOR_END__ - __CTOR_LIST__) / - )
*(.ctors)
LONG()
__CTOR_END__ = .;
__DTOR_LIST__ = .;
LONG((__DTOR_END__ - __DTOR_LIST__) / - )
*(.dtors)
LONG()
__DTOR_END__ = .;

符号__CTOR_LIST__标志者全局构造器的开始,符号__DTOR_LIST标志着构造器的结束。列表中的第一个关键字代表条目的个数,后面紧跟者是构造器和解析器的地址。最后是一个零字符。编译器必须排队去执行这些代码。

GNU编译器通常通过一个子程序__main函数前面调用constructor,__main在被调用时会自动的插入到main函数的起始代码中。同样的是,GNU通过运行atexit来调用destructors,或者是通过函数exit来直接调用。

参考文档:

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/4/html/Using_ld_the_GNU_Linker/sections.html