__attribute__((constructor)) 与 __attribute__((destructor)) 是 GCC 中用来修饰函数的,constructor 可以使被修饰的函数在 main() 执行前被调用,destructor 可以使被修饰的函数在 main() 执行结束或 exit() 调用结束后被执行。
__attribute__((constructor)) void constructor_func() {
// ...
}
__attribute__((destructor)) void destructor_func() {
// ...
}
一个程序中可以存在多个 constructor 和 destructor,使用优先级区分执行顺序,数字越小表示优先级越高(100 以内的优先级为保留数字不能设置)。constructor 中优先级越高越靠前执行,destructor 中优先级越高越靠后执行。不加优先级参数相当于最低优先级。
__attribute__((constructor(priority)))) void constructor_func() {
// ...
}
__attribute__((destructor(priority)))) void destructor_func() {
// ...
}
与 atexit() 同时使用时,atexit() 定义的函数会在 destructor 之前执行,如下例子:
#include <stdio.h>
#include <stdlib.h>
void atexit_func (void)
{
printf("atexit_func\n");
}
__attribute__((constructor)) void constructor_func (void)
{
printf("constructor_func\n");
}
__attribute__((constructor(105))) void constructor_func_105 (void)
{
printf("constructor_func 105\n");
}
__attribute__((constructor(106))) void constructor_func_106 (void)
{
printf("constructor_func 106\n");
}
__attribute__((constructor(107))) void constructor_func_107 (void)
{
printf("constructor_func 107\n");
}
__attribute__((constructor(1007))) void constructor_func_1007 (void)
{
printf("constructor_func 1007\n");
}
__attribute__((destructor)) void destructor_func (void)
{
printf("destructor_func\n");
}
__attribute__((destructor(105))) void destructor_func_105 (void)
{
printf("destructor_func 105\n");
}
__attribute__((destructor(106))) void destructor_func_106 (void)
{
printf("destructor_func 106\n");
}
__attribute__((destructor(107))) void destructor_func_107 (void)
{
printf("destructor_func 107\n");
}
__attribute__((destructor(1007))) void destructor_func_1007 (void)
{
printf("destructor_func 1007\n");
}
int main (int argc, char *argv[])
{
atexit(atexit_func);
return (0);
}
执行结果: