__attribute__((constructor))和__attribute__((destructor))

来源:互联网 发布:windows 10卸载office 编辑:程序博客网 时间:2024/05/20 18:02

我们有时候会在函数定义前面发现有__attribute__((constructor))或者__attribute__((destructor))的标签。 

这是gcc为函数提供了几种类型的属性:构造函数(constructors)和析构函数(destructors)。

一般我们都是以main函数作为总的入口,如果想在main函数之前,执行的某个函数,可以使用这个属性。

__attribute__((constructor))//定义的函数会在main之前被调用

__attribute__((destructor))//定义的函数会在main之后被调用

#include<stdio.h> __attribute__((constructor)) void fun0() {    printf("i am fun0\n"); } __attribute__((destructor)) void fun1() {    printf("i am fun1\n");  } int main(int argc, char **argv) {    printf("i am main\n");    return 0; }

则函数的调用顺序为 fun0 main fun1。输出如下:

i am fun0i am maini am fun1

我们常见的用到注册回调函数,但是又不确定,有哪些回调函数需要注册,但是又想在main函数中直接使用所有的回调函数,那么就可以不用在main里面去注册,在额外的c中注册需要使用的回调函数,然后在函数前面加上__attribute__((constructor))即可,这样在main函数执行之前,额外增加的回调函数就会被注册,则有main函数中就可以直接使用了。



阅读全文
0 0
原创粉丝点击