Gcc扩展:__attribute__((constructor))

__attribute__((constructor)),看样子又是Gcc的扩展,从注释知道这个关键字的作用是让被修饰函数在main函数开始之前调用。
不过,还是顺便好奇了一下下,翻了一下Gcc的手册,由于我测试机器上的Gcc版本是4.1.1,所以查看了4.1.2版本的文档。
对于__attribute__ ,解释如下:
 
Declaring Attributes of Functions
 
In GNU C, you declare certain things about functions called in your program which help
the compiler optimize function calls and check your code more carefully.
The keyword __attribute__ allows you to specify special attributes when making
a declaration. This keyword is followed by an attribute specification inside double
parentheses. The following attributes are currently defined for functions on all targets:
noreturn, returns_twice, noinline, always_inline, flatten, pure, const, nothrow,
sentinel, format, format_arg, no_instrument_function, section, constructor,
destructor, used, unused, deprecated, weak, malloc, alias, warn_unused_result,
nonnull and externally_visible. Several other attributes are defined for functions
on particular target systems. Other attributes, including section are supported for
variables declarations and for types
 
You may also specify attributes with ‘__’ preceding and following each keyword. This
allows you to use them in header files without being concerned about a possible macro of
the same name. For example, you may use __noreturn__ instead of noreturn.
 
这里讲的很清楚,我就不解释了。如蓝色部分所示,__attribute__除了可以修饰constructor,还可以修饰其他很多功能。
 
constructor功能解释如下:
 
constructor
destructor
The constructor attribute causes the function to be called automatically before
execution enters main (). Similarly, the destructor attribute causes the
function to be called automatically after main () has completed or exit () has
been called. Functions with these attributes are useful for initializing data that
will be used implicitly during the execution of the program.
These attributes are not currently implemented for Objective-C.
 
其他功能,就不贴出来了。

写个小程序测试一下:
$ cat test.c 
#include <stdio.h>

int main()
{
    printf("this is the first line in the main()!\n");
    
    return 0;
}

__attribute__((constructor))
void run_before_main()
{
    printf("run before main!!\n");
}

$ gcc test.c 
$ ./a.out 
run before main!!

this is the first line in the main()!


转载:http://filwmm1314.blog.163.com/blog/static/218259192012121225132/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值