c++:_attribute_ 使用:

来源:互联网 发布:淘宝女装店铺简介 编辑:程序博客网 时间:2024/06/05 06:24

GNU C的一大特色(却不被初学者所知)就是attribute机制。attribute可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。
attribute书写特征是:attribute前后都有两个下划线,并切后面会紧跟一对原括弧,括弧里面是相应的attribute参数。
attribute语法格式为:
attribute ((attribute-list))
其位置约束为:
放于声明的尾部“;”之前。
函数属性(Function Attribute)
函数属性可以帮助开发者把一些特性添加到函数声明中,从而可以使编译器在错误检查方面的功能更强大。attribute机制也很容易同非GNU应用程序做到兼容之功效。
GNU CC需要使用 –Wall编译器来击活该功能,这是控制警告信息的一个很好的方式。下面介绍几个常见的属性参数。
描述函数属性的几个重要的关键字:

void noreturnfun() attribute((noreturn));//函数不会返回。
void centon() attribute((alias(“__centon”)));//设置函数别名,函数是__cencon,别名是centon.
void main_enter() attribute((constructor));//main_enter函数在进入main函数前调用
void main_exit() attribute((destructor));//main_exit函数在main函数返回后调用
void fun() attribute ((noinline));//fun函数不能作为inline函数优化
void fun() attribute ((section(“specials”)));//将函数放到specials段中,而不是通常的text段中
no_instrument_function、constructor和destructor关键字主要用于剖析(profiling)源代码的。
attribute(format(archetype,string-index,first-to-check)): format attribute提供了依照printf, scanf, strftime, strfmon类型函数的参数格式对目标函数进行类型的检查.
attribute((weak)): weak symbol,弱符号. 若存在两个相同的全局符号时,会引发重定义错误. 如果使用weak attribute,则当weak symbol和non-weak symbol同时存在的时候,linker会使用non-weak symbol.若只有weak symbol存在的时候则只使用weak symbol.
attribute((deprecated)): deprecated,弃用. 如果在源文件在任何地方地方使用deprecated attribute函数,编译器将会发出警告.
attribute((aligned(ALIGNMENT))): 指定变量或结构体最小字节对齐数,以byte为单位.ALIGNMENT: 指定的字节对齐操作数.
attribute((cleanup(cleanup_function)): 当一个变量的作用域消失时,便会执行后面的clean_function函数.
attribute((packed)): 使变量或者是结构体按照最小的对齐方式,对于变量是1byte对齐,对于字段,也就是field指bit对齐.

0 0
原创粉丝点击