发现一个好玩的C语言特性,在main函数调用之前和调用之后也可以执行一些构造和析构的操作,一般用来初始化数据和资源回收。
先看下面的代码:
tcnst.c:
// gcc -o test tcnst.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void bf_print() __attribute__((constructor)) ;
void af_print() __attribute__((destructor)) ;
void bf_print() {
printf("bfbfbfbfbefore main\n") ;
}
void af_print() {
printf("afafafafafter main\n") ;
}
int main(int argc, char * argv[]) {
sleep(1) ;
printf("I am main\n") ;
sleep(1) ;
return 0 ;
}
编译执行:

从上边的运行结果看出来,定义函数时,使用 __attribute__((constructor))
修饰则会在main之前执行;而使用 __attribute__((destructor))
修饰则会在main运行结束之后执行。
发表回复