c语言中constructor和destructor的用法


__ attribute __((constructor)): 在main函数被调用之前调用
注:调用之前,各个全局变量已经完成初始化。也就是说,这些函数是在全局变量初始化之后,main函数之前调用的。这一点是非常重要的,否则可能会引起很多的问题。

__ attribute __((destructor)): 在main函数被调用之后调用

例子

#include<stdio.h>

__attribute__((constructor)) void before_main() 
{
    printf("before mainn");
}

 __attribute__((destructor)) void after_main() 
{
    printf("after mainn");
}
/* 主函数 */
 int main(int argc, char **argv) 
{
    printf("in mainn");
    return 0;
}

参考:
__attribute__中constructor和destructor[总结]