c语言的__attribute__

adtxl
2020-09-15 / 0 评论 / 2,996 阅读 / 正在检测是否收录...

[TOC]

转载:
https://blog.csdn.net/qlexcel/article/details/92656797
https://www.cnblogs.com/embedded-linux/p/5801999.html

一、介绍

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

\_\_attribute\_\_ 书写特征是:\_\_attribute\_\_ 前后都有两个下划线,并切后面会紧跟一对原括弧,\_\_attribute\_\_ 参数。

\_\_attribute\_\_ 语法格式为:\_\_attribute\_\_ ((attribute-list))

\_\_attribute\_\_ 也可以对结构体(struct )或共用体(union )进行属性设置。大致有六个参数值可以被设定,即:aligned, packed, transparent_union, unused, deprecated 和 may_alias 。

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

二、__attribute__参数介绍

  • 1.aligned

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

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

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

该声明将强制编译器确保(尽它所能)变量类 型为struct S 或者int32_t 的变量在分配空间时采用8 字节对齐方式。
如上所述,你可以手动指定对齐的格式,同 样,你也可以使用默认的对齐方式。如果aligned 后面不紧跟一个指定的数字值,那么编译器将依据你的目标机器情况使用最大最有益的对齐方式。例如:

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

这里,如果sizeof (short )的大小为2 (byte ),那么,S 的大小就为6 。取一个2 的次方值,使得该值大于等于6 ,则该值为8 ,所以编译器将设置S 类型的对齐方式为8 字节。
ligned 属性使被设置的对象占用更多的空间,相反的,使用packed 可以减小对象占用的空间。
需要注意的是,attribute 属性的效力与你的连接器也有关,如果你的连接器最大只支持16 字节对齐,那么你此时定义32 字节对齐也是无济于事的。

  • 2.packed

使用该属性对struct 或者union 类型进行定义,设定其类型的每一个变量的内存约束。当用在enum 类型 定义时,暗示了应该使用最小完整的类型(it indicates that the smallest integral type should be used)。
下面的例子中,packed_struct 类型的变量数组中的值将会紧紧的靠在一起,但内部的成员变量s 不会被“pack” ,如果希望内部的成员变量也被packed 的话,unpacked-struct 也需要使用packed 进行相应的约束。

struct unpacked_struct
{
      char c;
      int i;
};

struct packed_struct
{
     char c;
     int  i;
     struct unpacked_struct s;
}__attribute__ ((__packed__));

下面的例子中使用\_\_attribute\_\_ 属性定义了一些结构体及其变量,并给出了输出结果和对结果的分析。

struct p
{
        int a;
        char b;
        short c;
}__attribute__((aligned(4))) pp;

struct m
{
        char a;
        int b;
        short c;
}__attribute__((aligned(4))) mm;

struct o
{
        int a;
        char b;
        short c;
}oo;

struct x
{
        int a;
        char b;
        struct p px;
        short c;
}__attribute__((aligned(8))) xx;

int main()
{
        printf("sizeof(int)=%d,sizeof(short)=%d.sizeof(char)=%d\n",sizeof(int),sizeof(short),sizeof(char));
        printf("pp=%d,mm=%d \n", sizeof(pp),sizeof(mm));
        printf("oo=%d,xx=%d \n", sizeof(oo),sizeof(xx));

        return 0;
}

输出结 果:

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

pp=8,mm=12

oo=8,xx=24

分析:
sizeof(pp):
sizeof(a)+sizeof(b)+sizeof(c)=4+1+1=6\<8 所以sizeof(pp)=8
sizeof(mm):
sizeof(a)+sizeof(b)+sizeof(c)=1+4+2=7
但是 a 后面需要用 3 个字节填充,但是 b 是 4 个字节,所以 a 占用 4 字节, b 占用 4 个字节,而 c 又要占用 4 个字节。所以 sizeof(mm)=12
sizeof(oo):
sizeof(a)+sizeof(b)+sizeof(c)=4+1+2=7
因为默 认是以4 字节对齐,所以sizeof(oo)=8
sizeof(xx):
sizeof(a)+ sizeof(b)=4+1=5
sizeof(pp)=8; 即xx 是采用8 字节对齐的,所以要在a ,b 后面添3 个空余字节,然后才能存储px ,
4+1+ (3 )+8+1=17
因为xx 采用的对齐是8 字节对齐,所以xx 的大小必定是8 的整数倍,即xx 的大小是一个比17 大又是8 的倍数的一个最小值,由此得到
17\<24 ,所以sizeof(xx)=24

  • 3.函数属性(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)));

其原因是,类成员函数的第一个参数实际上一个“隐身”的“this”指针。(有点C++基础的都知道点this指针,不知道你在这里还知道吗?)
这里给出测试用例:attribute.c,代码如下:

1:
2:extern void myprint(const char *format,...) __attribute__((format(printf,1,2)));
3:
4:void 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:}

运行$gcc –Wall –c attribute.c attribute后,输出结果为:
attribute.c: In function 'test':
attribute.c: 7: warning: format argument is not a pointer (arg 2)
attribute.c: 9: warning: format argument is not a pointer (arg 2)
attribute.c: 9: warning: too few arguments for format
如果在attribute.c中的函数声明去掉\_\_attribute\_\_((format(printf,1,2))),再重新编译,既运行$gcc –Wall –c attribute.c attribute后,则并不会输出任何警告信息。
注意,默认情况下,编译器是能识别类似printf的“标准”库函数。

  • \_\_attribute\_\_ noreturn

该属性通知编译器函数从不返回值,当遇到类似函数需要返回值而却不可能运行到返回值处就已经退出来的情况,该属性可以避免出现错误信息。
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));
之后,编译不会再出现警告信息。

  • \_\_attribute\_\_ const

该属性只能用于带有数值类型参数的函数上。当重复调用带有数值参数的函数时,由于返回值是相同的,所以此时编译器可以进行优化处理,除第一次需要运算外, 其它只需要返回第一次的结果就可以了,进而可以提高效率。该属性主要适用于没有静态状态(static state)和副作用的一些函数,并且返回值仅仅依赖输入的参数。
为了说明问题,下面举个非常“糟糕”的例子,该例子将重复调用一个带有相同参数值的函数,具体如下:

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

通过添加\_\_attribute\_\_((const))声明,编译器只调用了函数一次,以后只是直接得到了相同的一个返回值。
事实上,const参数不能用在带有指针类型参数的函数中,因为该属性不但影响函数的参数值,同样也影响到了参数指向的数据,它可能会对代码本身产生严重甚至是不可恢复的严重后果。
并且,带有该属性的函数不能有任何副作用或者是静态的状态,所以,类似getchar()或time()的函数是不适合使用该属性的。

  • 关于linux内核中的"\_\_attribute\_\_ ((packed))"

引用:
\_\_attribute\_\_ ((packed)) 的作用就是告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐。

#define __u8    unsigned char
#define __u16   unsigned short
/* __attribute__ ((packed)) 的位置约束是放于声明的尾部“;”之前 */
struct str_struct{
        __u8    a;
        __u8    b;
        __u8    c;
        __u16   d;
} __attribute__ ((packed));
/*  当用到typedef时,要特别注意__attribute__ ((packed))放置的位置,相当于:
  *  typedef struct str_stuct str;
  *  而struct str_struct 就是上面的那个结构。
  */
typedef struct {
        __u8    a;
        __u8    b;
        __u8    c;
        __u16   d;
} __attribute__ ((packed)) str;
/* 在下面这个typedef结构中,__attribute__ ((packed))放在结构名str_temp之后,其作用是被忽略的,注意与结构str的区别。*/
typedef struct {
        __u8    a;
        __u8    b;
        __u8    c;
        __u16   d;
}str_temp __attribute__ ((packed));
typedef struct {
        __u8    a;
        __u8    b;
        __u8    c;
        __u16   d;
}str_nopacked;
int main(void)
{
        printf("sizeof str = %d\n", sizeof(str));
        printf("sizeof str_struct = %d\n", sizeof(struct str_struct));
        printf("sizeof str_temp = %d\n", sizeof(str_temp));
        printf("sizeof str_nopacked = %d\n", sizeof(str_nopacked));
        return 0;
}

编译运行:
引用:
[root@localhost root]# ./packedtest
sizeof str = 5
sizeof str_struct = 5
sizeof str_temp = 6
sizeof str_nopacked = 6

packed属性:使用该属性可以使得变量或者结构体成员使用最小的对齐方式,即对变量是一字节对齐,对域(field)是位对齐。

  • 4.at

绝对定位,可以把变量或函数绝对定位到Flash中,或者定位到RAM。
1)、定位到flash中,一般用于固化的信息,如出厂设置的参数,上位机配置的参数,ID卡的ID号,flash标记等等

const u16 gFlashDefValue[512] __attribute__((at(0x0800F000))) = {0x1111,0x1111,0x1111,0x0111,0x0111,0x0111};//定位在flash中,其他flash补充为00
const u16 gflashdata__attribute__((at(0x0800F000))) = 0xFFFF;

2)、定位到RAM中,一般用于数据量比较大的缓存,如串口的接收缓存,再就是某个位置的特定变量

u8 USART2_RX_BUF[USART2_REC_LEN] __attribute__ ((at(0X20001000)));//接收缓冲,最大USART_REC_LEN个字节,起始地址为0X20001000.

注意:

1)、绝对定位不能在函数中定义,局部变量是定义在栈区的,栈区由MDK自动分配、释放,不能定义为绝对地址,只能放在函数外定义。
2)、定义的长度不能超过栈或Flash的大小,否则,造成栈、Flash溢出。

  • 5.section

提到section,就得说RO RI ZI了,在ARM编译器编译之后,代码被划分为不同的段,RO Section(ReadOnly)中存放代码段和常量,RW Section(ReadWrite)中存放可读写静态变量和全局变量,ZI Section(ZeroInit)是存放在RW段中初始化为0的变量。
于是本文的大体意思就清晰了,\_\_attribute\_\_((section("section_name"))),其作用是将作用的函数或数据放入指定名为"section_name"对应的段中。
1)、编译时为变量指定段:

__attribute__((section("name")))
RealView Compilation Tools for µVision Compiler Reference Guide Version 4.0 
 
Home > Compiler-specific Features > Variable attributes > __attribute__((section("name"))) 
 
4.5.6. __attribute__((section("name")))
Normally, the ARM compiler places the objects it generates in sections like data and bss. However, you might require additional data sections or you might want a variable to appear in a special section, for example, to map to special hardware. The section attribute specifies that a variable must be placed in a particular data section. If you use the section attribute, read-only variables are placed in RO data sections, read-write variables are placed in RW data sections unless you use the zero_init attribute. In this case, the variable is placed in a ZI section.
 
Note
This variable attribute is a GNU compiler extension supported by the ARM compiler.
 
Example
/* in RO section */
const int descriptor[3] __attribute__ ((section ("descr"))) = { 1,2,3 };
/* in RW section */
long long rw[10] __attribute__ ((section ("RW")));
/* in ZI section *
long long altstack[10] __attribute__ ((section ("STACK"), zero_init));/

2)、编译时为函数指定段

__attribute__((section("name")))
RealView Compilation Tools for µVision Compiler Reference Guide Version 4.0 
 
Home > Compiler-specific Features > Function attributes > __attribute__((section("name"))) 
 
4.3.13. __attribute__((section("name")))
The section function attribute enables you to place code in different sections of the image.
 
Note
This function attribute is a GNU compiler extension that is supported by the ARM compiler.
 
Example
In the following example, Function_Attributes_section_0 is placed into the RO section new_section rather than .text.
 
void Function_Attributes_section_0 (void) __attribute__ ((section ("new_section")));
void Function_Attributes_section_0 (void)
{
    static int aStatic =0;
    aStatic++;
}
In the following example, section function attribute overrides the #pragma arm section setting.
 
#pragma arm section code="foo"
  int f2()
  {
      return 1;
  }                                  // into the 'foo' area
 
  __attribute__ ((section ("bar"))) int f3()
  {
      return 1;
  }                                  // into the 'bar' area
 
  int f4()
  {
      return 1;
  }                                  // into the 'foo' area
#pragma arm section
  • 6.多个属性组合使用

u8 FileAddr[100] __attribute__ ((section ("FILE_RAM"), zero_init,aligned(4)));    
0

评论 (0)

取消