[gcc]gcc之attribute关键字


一、__attribute__关键字

  1. __attribute__关键字主要是用来在函数或数据声明中设置其属性。给函数设置属性的主要目的在于让编译器进行优化。如函数声明中添加
    __attribute__((noreturn)),就是告诉编译器这个函数不会返回给调用者,以便编译器在优化时去掉不必要的函数返回代码。

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

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

__attribute__语法格式为:

__attribute__ ((attribute-list))

二、__attribute__((packed))

__attribute__ ((packed)) 的作用是告诉编译器取消结构体在编译过程中的优化对齐,按照实际占用字节数进行对齐,这是GCC特有的语法。这个功能是跟操作系统没关系,跟编译器有关,gcc编译器不是紧凑模式的,我在windows下,用vc的编译器也不是紧凑的,用tc的编译器就是紧凑的。例如:

在TC下:struct my{ char ch; int a;} sizeof(int)=2;sizeof(my)=3;(紧凑模式)

在GCC下:struct my{ char ch; int a;} sizeof(int)=4;sizeof(my)=8;(非紧凑模式)

在GCC下:struct my{ char ch; int a;}__attrubte__ ((packed)) sizeof(int)=4;sizeof(my)=5

用途:

  1. 减少空间占用
  2. 统一在不同平台结构体大小(防止有些对齐有些不对齐),以便进行基于数据结构的网络通讯。

四、__attribute__((section("name")))

其作用是将作用的函数或数据放入指定名为"name"的段。

五、__attribute__((used))

unused: 该函数可能未使用,编译器可以不对其产生waring输出。This attribute, attached to a function, means that the function is meant to be possibly unused. GCC will not produce a warning for this function.
used: 即使这个函数看起来未使用,也要对其编译。This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly.

参考链接:

  1. __attribute__((packed))详解
  2. 跨平台时基于数据结构的网络通信
  3. gcc __attribute__((section("section_name"))) 使用方法
发布了183 篇原创文章 · 获赞 106 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/qq_20515461/article/details/101773351
gcc
今日推荐