您的位置:首页 > 大数据 > 人工智能

__attribute__((constructor)) 修饰的函数在main函数之前执行

2015-07-24 17:45 525 查看
最近研究qemu,初始化的时候有类似的代码:

#define module_init(function, type)                                         \
static void __attribute__((constructor)) do_qemu_init_ ## function(void) {  \
register_module_init(function, type);                                   \
}


do_qemu_init_** 想必是模块的初始化了,但是却没有调用 do_qemu_init的地方,奇了怪了,为什么呢?

仔细看看这个函数,修饰符中包含了 __attribute__((constructor)),估计就是这个家伙干的!

写代码测试之:

#include <stdio.h>
#include <stdlib.h>

void static __attribute__((constructor)) before_main()
{
printf("before main\n");
}

void static __attribute__((destructor)) after_main()
{
printf("after main\n");
}

int main(int argc, char** argv)
{
printf("hello world!\n");
}


编译执行:
root@mothership:/home/source/test# gcc a.c -o a
root@mothership:/home/source/test# ./a
before main
hello world!
after main
root@mothership:/home/source/test#


果然是这样,

__attribute__((constructor)) 修饰的函数在main函数之前执行

__attribute__((destructor)) 修饰的函数在main函数之后执行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: