关于GCC的__attribute__ ((constructor))
2013-06-18 15:46
429 查看
关于GCC的__attribute__ ((constructor))
static void start(void) __attribute__
((constructor));
static void stop(void) __attribute__
((destructor));
带有"构造函数"属性的函数将在main()函数之前被执行,而声明为"析构函数"属性的函数则将在main()退出时执行。
下面给出一个简单的程序作为例子:
/* test.c */
#include<stdio.h>
__attribute__((constructor)) void before_main()
{
printf("before main/n");
}
__attribute__((destructor)) void after_main()
{
printf("after main/n");
}
int main()
{
printf("in main/n");
return 0;
}
$ gcc test.c -o test
$ ./test
before main
in main
after main
根据上面的代码以及输出结果,我们可以猜到__attribute__((constructor))表示这段代码将在main函数前调用,就像在C++里面的全局变量类的构造一样.
gcc为函数提供了几种类型的属性,其中包含:构造函数(constructors)和析构函数(destructors)。
程序员应当使用类似下面的方式来指定这些属性:
static void start(void) __attribute__((constructor));
static void stop(void) __attribute__
((destructor));
带有"构造函数"属性的函数将在main()函数之前被执行,而声明为"析构函数"属性的函数则将在main()退出时执行。
下面给出一个简单的程序作为例子:
/* test.c */
#include<stdio.h>
__attribute__((constructor)) void before_main()
{
printf("before main/n");
}
__attribute__((destructor)) void after_main()
{
printf("after main/n");
}
int main()
{
printf("in main/n");
return 0;
}
$ gcc test.c -o test
$ ./test
before main
in main
after main
根据上面的代码以及输出结果,我们可以猜到__attribute__((constructor))表示这段代码将在main函数前调用,就像在C++里面的全局变量类的构造一样.
相关文章推荐
- 关于GCC的__attribute__(constructor)
- 关于GCC的__attribute__ ((constructor))
- 关于GCC的__attribute__ ((constructor))
- 关于GCC的__attribute__(constructor)
- GCC __attribute__((constructor)|(destructor))
- GCC __attribute__((constructor)|(destructor))
- gcc 函数属性 __attribute__ ((constructor))使用
- gcc的__attribute__ ((constructor))和__attribute__ ((destructor))
- Gcc扩展:__attribute__((constructor))
- __attribute__((constructor)) 高版本gcc不执行
- GCC的__attribute__ ((constructor))和__attribute__ ((destructor))
- gcc下__attribute__ ((constructor))和__attribute__ ((destructor))的使用
- __attribute__((weak)) 博大精深的gcc ------ 关于弱符号的用法
- gcc中__attribute__ ((constructor(101)))做成.a库成功链接
- gcc下__attribute__ ((constructor))和__attribute__ ((destructor))的使用
- GCC __attribute__((constructor)|(destructor))
- GCC中 __attribute__((constructor)|(destructor))
- GCC __attribute__((constructor和(destructor)) (Cygwin)
- gcc __attribute__关键字举例之constructor/destructor
- GCC的__attribute__ ((constructor))和__attribute__ ((destructor))