跳过正文

_Attribute_

·3 分钟
目录

概述
#

GNU C 的一大特色就是__attribute__ 机制。attribute 可以设置函数属性(Function Attribute )、变量属性(Variable Attribute )和类型属性(Type Attribute )。

主要在object-c 的源码中可以见到,有助于源码的理解。

  • attribute’ 书写特征是:attribute 前后都有两个下划线,并切后面会紧跟一对原括弧,括弧里面是相应的__attribute__ 参数。

  • attribute’ 语法格式为:"attribute ((attribute-list))",其位置约束为:放于函数声明的尾部“ ;” 之前。

使用__attribute__描述函数的属性
#

函数属性可以帮助开发者把一些特性添加到函数声明中,从而可以使编译器在错误检查方面的功能更强大。一般在attribute后边。

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 lconst char *format,...) 
    __attribute__((format(printf,2,3)));
    //需要特别注意的是,如果myprint是一个函数的成员函数,那么m和n的值可有点“悬乎”了,例如:
    //m=3;n=4
    extern void myprint(int lconst char *format,...) 
    __attribute__((format(printf,3,4)));
    //其原因是,类成员函数的第一个参数实际上一个“隐身”的“this”指针。(有点C++基础的都知道点this指针,不知道你在这里还知道吗?)
    

    这里给出测试用例:attribute.c,代码如下:

2extern void myprint(const char *format,...) 
__attribute__((format(printf,1,2)));
3
4void test()
5{
6     myprint("i=%d\n",6);
7     myprint("i=%s\n",6);
8     myprint("i=%s\n","abc");
9     myprint("%s,%d,%d\n",1,2);
10}

attribute 相关其他属性
#

不只是上面format。attribute const 。该属性只能用于带有数值类型参数的函数上。当重复调用带有数值参数的函数时,由于返回值是相同的,所以此时编译器可以进行优化处理,除第一次需要运算外,其它只需要返回第一次的结果就可以了,进而可以提高效率。该属性主要适用于没有静态状态(static state)和副作用的一些函数,并且返回值仅仅依赖输入的参数。

extern int square(int n) __attribute__((const)); ...  for (i = 0; i < 100; i++ ){   total += square(5) + i;  }

参考链接