Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1148441
  • 博文数量: 115
  • 博客积分: 950
  • 博客等级: 准尉
  • 技术积分: 1734
  • 用 户 组: 普通用户
  • 注册时间: 2011-12-08 20:46
文章分类

全部博文(115)

文章存档

2015年(5)

2014年(28)

2013年(42)

2012年(40)

分类: LINUX

2015-04-07 16:52:54

以下内容,基本转载自网络。
其中稍许添加了个人的测试以及感想。具体转载的位置,可以参考文章最后

1. __attribute__

GNU C的一大特色(却不被初学者所知)就是__attribute__机制。

__attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)
以上三种函数/变量/类型属性有各自不同的具体属性

__attribute__前后都有两个下划线,并且后面会紧跟一对原括弧,括弧里面是相应的__attribute__参数

__attribute__语法格式为:

__attribute__ ( ( attribute-list ) )

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

__attribute__机制也很容易同非GNU应用程序做到兼容。

GNU CC需要使用 –Wall,这是控制警告信息的一个很好的方式。下面介绍几个常见的属性参数。

 
Function Attribute
Function Attribute包含的类型很多,以下主要介绍部分常用的属性,比如 format,const,constructor,destructor,noreturn,section,unused

2. format

首先一段英文备注

点击(此处)折叠或打开

  1. This __attribute__ allows assigning printf-like or scanf-like characteristics to the declared function, and this enables the compiler to check the format string against the parameters provided throughout the code. This is exceptionally helpful in tracking down hard-to-find bugs.

  2. There are two flavors:

  3.     __attribute__((format(printf,m,n)))
  4.     __attribute__((format(scanf,m,n)))

  5. but in practice we use the first one much more often.

  6. The (m) is the number of the "format string" parameter, and (n) is the number of the first variadic parameter. To see some examples:

  7. /* like printf() but to standard error only */
  8. extern void eprintf(const char *format, ...)
  9.     __attribute__((format(printf, 1, 2))); /* 1=format 2=params */

  10. /* printf only if debugging is at the desired level */
  11. extern void dprintf(int dlevel, const char *format, ...)
  12.     __attribute__((format(printf, 2, 3))); /* 2=format 3=params */

  13. With the functions so declared, the compiler will examine the argument lists

  14. $ cat test.c
  15. 1 extern void eprintf(const char *format, ...)
  16. 2 __attribute__((format(printf, 1, 2)));
  17. 3
  18. 4 void foo()
  19. 5 {
  20. 6 eprintf("s=%s\n", 5); /* error on this line */
  21. 7
  22. 8 eprintf("n=%d,%d,%d\n", 1, 2); /* error on this line */
  23. 9 }

  24. $ cc -Wall -c test.c
  25. test.c: In function `foo

该属性可以使编译器检查函数声明和函数实际调用参数之间的格式化字符串是否匹配
。它可以给被声明的函数加上类似printf或者scanf的特征,该功能十分有用,尤其是处理一些很难发现的bug


format的语法格式为:

format ( archetype,  string-index,  first-to-check )

format属性告诉编译器,按照printfscanfstrftimestrfmon的参数表格式规则对该函数的参数进行检查。archetype:指定是哪种风格;

string-index:指定传入函数的第几个参数是格式化字符串;

first-to-check:指定从函数的第几个参数开始按上述规则进行检查。

具体使用格式如下:

__attribute__( ( format( printfmn ) ) )

__attribute__( ( format( scanfmn ) ) )

其中参数mn的含义为:

m表明第几个参数为格式化字符串(format string);format string的含义,可以 man printf。

n参数集合中的第一个,即参数“…”里的第一个参数在函数参数总数排在第几

在使用上,__attribute__((format(printf,m,n)))是常用的,而另一种却很少见到。

 

3. noreturn

同样,首先是英文解释

点击(此处)折叠或打开

  1. This attribute tells the compiler that the function won't ever return, and this can be used to suppress errors about code paths not being reached. The C library functions abort() and exit() are both declared with this attribute:

  2. extern void exit(int) __attribute__((noreturn));
  3. extern void abort(void) __attribute__((noreturn));

  4. Once tagged this way, the compiler can keep track of paths through the code and suppress errors that won't ever happen due to the flow of control never returning after the function call.

  5. In this example, two nearly-identical C source files refer to an "exitnow()" function that never returns, but without the __attribute__ tag, the compiler issues a warning. The compiler is correct here, because it has no way of knowing that control doesn't return.

  6. $ cat test1.c
  7. extern void exitnow();

  8. int foo(int n)
  9. {
  10.         if ( n > 0 )
  11.     {
  12.                 exitnow();
  13.         /* control never reaches this point */
  14.     }
  15.         else
  16.                 return 0;
  17. }

  18. $ cc -c -Wall test1.c
  19. test1.c: In function `foo':
  20. test1.c:9: warning: this function may return with or without a value

  21. But when we add __attribute__, the compiler suppresses the spurious warning:

  22. $ cat test2.c
  23. extern void exitnow() __attribute__((noreturn));

  24. int foo(int n)
  25. {
  26.         if ( n > 0 )
  27.                 exitnow();
  28.         else
  29.                 return 0;
  30. }

  31. $ cc -c -Wall test2.c
  32. no
有时候会发现,其实原文会更能让人了解事情的本质,翻译多少会改变些什么
该属性通知编译器函数从不返回值


当遇到函数需要返回值却还没运行到返回值处就已退出来的情况,该属性可以避免出现错误信息。C库函数中的abort()和exit()的声明格式就采用了这种格式

extern void  exit(int)   __attribute__( ( noreturn ) );

extern void  abort(void)  __attribute__( ( noreturn ) );

为了方便理解,大家可以参考如下的例子:

//name: noreturn.c     ;测试__attribute__((noreturn))

extern void  myexit();

int  test( int  n )

{

    if ( n > 0 )

    {

            myexit();

            /* 程序不可能到达这里 */

    }

    else

    {

           return 0;

    }

}

编译$gcc –Wall –c noreturn.c  显示的输出信息为:

noreturn.c: In function `test':

noreturn.c:12: warning: control reaches end of non-void function

警告信息也很好理解,因为你定义了一个有返回值的函数test却有可能没有返回值,程序当然不知道怎么办了!加上__attribute__((noreturn))则可以很好的处理类似这种问题。把extern void myexit();修改为:

extern void  myexit() __attribute__((noreturn));

之后,编译不会再出现警告信息。

 

4. const

点击(此处)折叠或打开

  1. This attribute marks the function as considering only its numeric parameters. This is mainly intended for the compiler to optimize away repeated calls to a function that the compiler knows will return the same value repeatedly. It applies mostly to math functions that have no static state or side effects, and whose return is solely determined by the inputs.

  2. In this highly-contrived example, the compiler normally must call the square() function in every loop even though we know that it's going to return the same value each time:

  3. extern int square(int n) __attribute__((const));

  4. ...
  5.     for (i = 0; i < 100; i++ )
  6.     {
  7.         total += square(5) + i;
  8.     }

  9. By adding __attribute__((const)), the compiler can choose to call the function just once and cache the return value.

  10. In virtually every case, const can't be used on functions that take pointers, because the function is not considering just the function parameters but also the data the parameters point to, and it will almost certainly break the code very badly in ways that will be nearly impossible to track down.

  11. Furthermore, the functions so tagged cannot have any side effects or static state, so things like getchar() or time() would behave very poorly under these circumstances.

该属性只能用于带有数值类型参数的函数上,当重复调用带有数值参数的函数时,由于返回值是相同的。所以此时编译器可以进行优化处理,除第一次需要运算外, 其它只需要返回第一次的结果。


该属性主要适用于没有静态状态(static state)和副作用的一些函数,并且返回值仅仅依赖输入的参数。为了说明问题,下面举个非常糟糕的例子,该例子将重复调用一个带有相同参数值的函数,具体如下:

extern int  square( int  n ) __attribute__ ( (const) );

for (i = 0; i < 100; i++ )                 

{      

       total += square (5) + i;            

}

添加__attribute__((const))声明,编译器只调用了函数一次,以后只是直接得到了相同的一个返回值。

事实上,const参数不能用在带有指针类型参数的函数中,因为该属性不但影响函数的参数值,同样也影响到了参数指向的数据,它可能会对代码本身产生严重甚至是不可恢复的严重后果。并且,带有该属性的函数不能有任何副作用或者是静态的状态,类似getchar()或time()的函数是不适合使用该属性。

 

5. finstrument-functions

该参数可以使程序在编译时,在函数的入口和出口处生成instrumentation调用。恰好在函数入口之后并恰好在函数出口之前,将使用当前函数的地址和调用地址来调用下面的profiling函数。(在一些平台上,__builtin_return_address不能在超过当前函数范围之外正常工作,所以调用地址信息可能对profiling函数是无效的)

void  __cyg_profile_func_enter( void  *this_fnvoid  *call_site );

void  __cyg_profile_func_exit( void  *this_fnvoid  *call_site );

其中,第一个参数this_fn是当前函数的起始地址,可在符号表中找到;第二个参数call_site是调用处地址。

 

6. instrumentation

也可用于在其它函数中展开的内联函数。从概念上来说,profiling调用将指出在哪里进入和退出内联函数。这就意味着这种函数必须具有可寻址形式。如果函数包含内联,而所有使用到该函数的程序都要把该内联展开,这会额外地增加代码长度。如果要在C 代码中使用extern inline声明,必须提供这种函数的可寻址形式。
可对函数指定no_instrument_function属性,在这种情况下不会进行 instrumentation操作。例如,可以在以下情况下使用no_instrument_function属性:上面列出的profiling函数、高优先级的中断例程以及任何不能保证profiling正常调用的函数。

no_instrument_function

如果使用了-finstrument-functions,将在绝大多数用户编译的函数的入口和出口点调用profiling函数。使用该属性,将不进行instrument操作。

 

7. constructor/destructor

若函数被设定为constructor属性,则该函数会在main()函数执行之前被自动的执行。类似的,若函数被设定为destructor属性,则该函数会在main()函数执行之后或者exit()被调用后被自动的执行。拥有此类属性的函数经常隐式的用在程序的初始化数据方面,这两个属性还没有在面向对象C中实现。

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. static void start(void) __attribute__ ((constructor));
  4. static void stop(void) __attribute__ ((destructor));

  5. int
  6. main(int argc, char *argv[])
  7. {
  8.         printf("start == %p\n", start);
  9.         printf("stop == %p\n", stop);

  10.         exit(EXIT_SUCCESS);
  11. }

  12. void
  13. start(void)
  14. {
  15.         printf("hello world!\n");
  16. }

  17. void
  18. stop(void)
  19. {
  20.         printf("goodbye world!\n");
  21. }

 


8. 同时使用多个属性

点击(此处)折叠或打开

  1. Multiple __attributes__ can be strung together on a single declaration, and this is not uncommon in practice. You can either use two separate __attribute__s, or use one with a comma-separated list:

  2. /* send printf-like message to stderr and exit */
  3. extern void die(const char *format, ...)
  4.     __attribute__((noreturn))
  5.     __attribute__((format(printf, 1, 2)));

  6. /*or*/

  7. extern void die(const char *format, ...)
  8.     __attribute__((noreturn, format(printf, 1, 2)));

  9. If this is tucked away safely in a library header file, all programs that call this function receive this checking.
可以在同一个函数声明里使用多个__attribute__,并且实际应用中这种情况是十分常见的。使用方式上,你可以选择两个单独的__attribute__,或者把它们写在一起,可以参考下面的例子:


extern void  die(const char *format ...)   __attribute__( (noreturn))   __attribute__((format(printf, 1, 2)) );

或者写成

extern void  die(const char *format...)    __attribute__( (noreturn,  format(printf, 1, 2)) );

如果带有该属性的自定义函数追加到库的头文件里,那么所以调用该函数的程序都要做相应的检查。

 

9. 和非GNU编译器的兼容性

点击(此处)折叠或打开

  1. Fortunately, the __attribute__ mechanism was cleverly designed in a way to make it easy to quietly eliminate them if used on platforms other than GNU C. Superficially, __attribute__ appears to have multiple parameters (which would typically rule out using a macro), but the two sets of parentheses effectively make it a single parameter, and in practice this works very nicely.

  2. /* If we're not using GNU C, elide __attribute__ */
  3. #ifndef __GNUC__
  4. # define __attribute__(x) /*NOTHING*/
  5. #endif

  6. Note that __attribute__ applies to function declarations, not definitions, and we're not sure why this is. So when defining a function that merits this treatment, an extra declaration must be used (in the same file):

  7. /* function declaration */
  8. void die(const char *format, ...) __attribute__((noreturn))
  9.                                   __attribute__((format(printf,1,2)));

  10. void die(const char *format, ...)
  11. {
  12.     /* function definition */
  13. }
__attribute__设计的非常巧妙,很容易作到和其它编译器保持兼容。也就是说,如果工作在其它的非GNU编译器上,可以很容易的忽略该属性。即使__attribute__使用了多个参数,也可以很容易的使用一对圆括弧进行处理,例如:


 /* 如果使用的是非GNU C, 那么就忽略__attribute__ */

#ifndef __GNUC__

      #define     __attribute__(x)     /* NOTHING * /

#endif

需要说明的是,__attribute__适用于函数的声明而不是函数的定义。所以,当需要使用该属性的函数时,必须在同一个文件里进行声明,例如:

/* 函数声明 */

void  die( const char *format ... ) __attribute__( (noreturn) )   __attribute__( ( format(printf12) ) );

void  die( const char *format... )

{   /* 函数定义 */  }

更多属性参考:

 
Variable Attribute
Variable Attribute主要有类似: aligned, packed,section等等

10. 变量属性(Variable Attributes

关键字__attribute__也可以对变量(variable)或结构体成员(structure field)进行属性设置。

在使用__attribute__参数时,你也可以在参数的前后都加上“__”(两个下划线),例如,使用__aligned__而不是aligned,这样,你就可以在相应的头文件里使用它而不用关心头文件里是否有重名的宏定义。
更多属性可以参考:

 
Type Attribute
Type Attribute的类型主要介绍如下:

11. 类型属性(Type Attribute

关键字__attribute__也可以对结构体(struct)或共用体(union)进行属性设置。

大致有六个参数值可以被设定:alignedpackedtransparent_unionunuseddeprecatedmay_alias

 

12. aligned (alignment)

该属性设定一个指定大小的对齐格式(以字节为单位),例如:

struct S { short f[3]; } __attribute__ ( ( aligned (8) ) );

typedef  int  more_aligned_int __attribute__ ( ( aligned (8) ) );

这里,如果sizeofshort)的大小为2byte),那么,S的大小就为6。取一个2的次方值,使得该值大于等于6,则该值为8,所以编译器将设置S类型的对齐方式为8字节。该声明将强制编译器确保(尽它所能)变量类型为struct S或者more-aligned-int的变量在分配空间时采用8字节对齐方式。

如上所述,你可以手动指定对齐的格式,同样,你也可以使用默认的对齐方式。例如:

struct S { short f[3]; } __attribute__ ( (aligned) );

上面,aligned后面不紧跟一个指定的数字值,编译器将依据你的目标机器情况使用最大最有益的对齐方式。

int  x __attribute__ ( (aligned (16) ) )  =  0;

编译器将以16字节(注意是字节byte不是位bit)对齐的方式分配一个变量。也可以对结构体成员变量设置该属性,例如,创建一个双字对齐的int对,可以这么写:

Struct  foo {  int  x[2] __attribute__ ( (aligned (8) ) );  };

选择针对目标机器最大的对齐方式,可以提高拷贝操作的效率。
aligned
属性使被设置的对象占用更多的空间,相反的,使用packed可以减小对象占用的空间。
需要注意的是,attribute属性的效力与你的连接器也有关,如果你的连接器最大只支持16字节对齐,那么你此时定义32字节对齐也是无济于事的。

 

13. packed

使用该属性可以使得变量或者结构体成员使用最小的对齐方式,即对变量是一字节对齐,对域(field)是位对齐。使用该属性对struct或者union类型进行定义,设定其类型的每一个变量的内存约束。当用在enum类型定义时,暗示了应该使用最小完整的类型 (it indicates that the smallest integral type should be used)。

下面的例子中,x成员变量使用了该属性,则其值将紧放置在a的后面:

struct  test

{

      char  a;

      int  x[2] __attribute__ ((packed));

};

下面的例子中,my-packed-struct类型的变量数组中的值将会紧紧的靠在一起,但内部的成员变量s不会被“pack”,如果希望内部的成员变量也被packedmy-unpacked-struct也需要使用packed进行相应的约束。

struct my_packed_struct

{

        char  c;

        int  i;

        struct  my_unpacked_struct  s;

}__attribute__ ( (__packed__) );

其它可选的属性值还可以是:cleanupcommonnocommondeprecatedmodesectionshared tls_modeltransparent_unionunusedvector_sizeweakdllimportdlexport等。

更多详细参考:

 

14. 变量属性与类型属性举例

下面的例子中使用__attribute__属性定义了一些结构体及其变量,并给出了输出结果和对结果的分析。
程序代码为:

struct  p

{

       int a;

       char b;

       char c;

}__attribute__( ( aligned(4) ) ) pp;

struct  q

{

       int a;

       char b;

       struct n qn;

       char c;

}__attribute__( ( aligned(8) ) ) qq;

int  main()

{

       printf("sizeof(int)=%dsizeof(short)=%dsizeof(char)=%d/n"sizeof(int)sizeof(short)sizeof(char));

       printf("pp=%dqq=%d /n" sizeof(pp)sizeof(qq));

       return 0;

}

输出结果:

sizeof(int)=4sizeof(short)=2sizeof(char)=1

pp=8qq=24

分析:

sizeof(pp):

sizeof(a)+ sizeof(b)+ sizeof(c)=4+1+1=6<2^3=8= sizeof(pp)

sizeof(qq):

sizeof(a)+ sizeof(b)=4+1=5

sizeof(qn)=8;

qn是采用8字节对齐的,所以要在ab后面添3个空余字节,然后才能存储qn

4+1+3+8+1=17

因为qq采用的对齐是8字节对齐,所以qq的大小必定是8的整数倍,即qq的大小是一个比17大又是8的倍数的一个最小值,由此得到

17<2^4+8=24= sizeof(qq)

更详细的介绍见:


################################REF#################################

 __attribute__使用的一些总结
__attribute__机制介绍


阅读(1136) | 评论(0) | 转发(0) |
0

上一篇:查看 GCC编译时头文件搜索路径

下一篇:没有了

给主人留下些什么吧!~~