__attribute__机制
GNU C 的一大特色(却不被初学者所知)就是__attribute__ 机制。 __attribute__可以 置
函数属性( FunctionAttribute )、 量属性( Variable Attribute)和 型属性( Type Attribute)。
__attribute__ 写特征是: __attribute__ 前后都有两个下划 ,并切后面会 跟一 原括弧,
括弧里面是相 的__attribute__ 参数。
__attribute__ 法格式 :
__attribute__ ((attribute-list))
其位置 束 :
放于声明的尾部“; ”之前。
函数属性( Function Attribute)
函数属性可以帮助开 者把一些特性添加到函数声明中, 从而可以使 器在 方面的功能更 大。 __attribute__ 机制也很容易同非 GNU 用程序做到兼容之功效。
GNU CC 需要使用 –Wall 器来 活 功能, 是控制警告信息的一个很好的方式。下面介 几个常 的属性参数。
__attribute__ format
该__attribute__属性可以 被声明的函数加上 似printf 或者 scanf 的特征,它可以使
器 函数声明和函数 用参数之 的格式化字符串是否匹配。 功能十分有用, 尤其
是 理一些很 的bug 。
format 的 法格式 :
format (archetype, string-index, first-to-check)
format 属性告 器,按照printf, scanf,
strftime 或 strfmon 的参数表格式 函数的参数 行 。“ archetype 指”定是哪种
格; “string-index”指定 入函数的第几个参数是格式化字符串;“first-to- check”指定从函数
的第几个参数开始按上述 行 。
具体使用格式如下:
__attribute__((format(printf,m,n)))
__attribute__((format(scanf,m,n)))
其中参数 m 与 n 的含 :
m:第几个参数 格式化字符串(format string);
n:参数集合中的第一个,即参数“?”里的第一个参数在函数参数 数排在第几,注意,有
函数参数里 有“ 身 ”的呢,后面会提到;
在使用上, __attribute__((format(printf,m,n)))是常用的,而另一种却很少 到。下面 例
明,其中 myprint 自己定 的一个 有可 参数的函数,其功能 似于printf :
//m=1 ; n=2
extern void myprint(const char *format,...) __attribute__((format(printf,1,2))); //m=2 ; n=3
extern void myprint(int l, const char *format,...)
__attribute__((format(printf,2,3)));
需要特别注意的是,如果myprint 是一个函数的成员函数,那么m 和 n 的值可有点 “悬乎 ”
了,例如:
//m=3 ; n=4
extern void myprint(int l, const char *format,...)
__attribute__((format(printf,3,4)));
2.3.1指定变量的属性
编译器的关键字__attribute__用来指定变量或结构位域的特殊属性。关键字后的
双括弧中的内容是属性说明。
下面是目前支持的变量属性:
address (addr)
aligned (alignment)
boot
deprecated
fillupper
far
mode (mode)
near
noload
packed
persistent
reverse (alignment)
section ("section -name")
secure
sfr (address)
space (space)
transparent_union
unordered
unused
weak
weak 也可以通过在关键字前后使用__ (双下划线)来指定属性(例如,用
__aligned__ 代替 aligned )。这样将使你在头文件中使用它们时不必考虑会出现与宏同名的情况。
要指定多个属性,可在双括弧内用逗号将属性分隔开,例如:
__attr