Blog
Blog copied to clipboard
GCC设置函数属性
最近在学习QEMU源码,碰到了GCC属性相关知识,在此记录下。
/* This should not be used directly. Use block_init etc. instead. */
#define module_init(function, type) \
static void __attribute__((constructor)) do_qemu_init_ ## function(void) \
{ \
register_module_init(function, type); \
}
首先看看__attribute__关键字,__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。 __attribute__语法格式为:attribute ( ( attribute-list ) )
这里的constructor
修饰类似于C++的构造函数,被它修饰的函数会在main函数执行之前别调用,相应的,被destructor
修饰的函数会在main函数执行后或exit执行完后调用,类似C++的析构函数。
示例:
#include <stdio.h>
#include <stdlib.h>
void __attribute__((constructor)) con_func()
{
printf("befor main: constructor is called..\n");
}
void __attribute__((destructor)) des_func()
{
printf("after main: destructor is called..\n");
}
int main()
{
printf("main func..\n");
return 0;
}
输出:
main.c
befor main: constructor is called..
main func..
after main: destructor is called..