'packed' attribute ignored [-Werror=attributes] 错误处理

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_35933684/article/details/100706328

修改一个项目上的编译告警,出现了'packed' attribute ignored [-Werror=attributes] 错误,很是惶恐,需要说明的是编译时如果不打开 -Werror是没有错误。因为定义是这样的。

typedef struct {
    int32_t mmap_addr;
    char tag[4]; /* 'P', 'R', 'E', ' ' */
}prelink_info_t __attribute__((packed)) ;

官方解释是这样的

This attribute, attached to a structunion, or C++ class type definition, specifies that each of its members (other than zero-width bit-fields) is placed to minimize the memory required. This is equivalent to specifying the packed attribute on each of the members.

When attached to an enum definition, the packed attribute indicates that the smallest integral type should be used. Specifying the -fshort-enums flag on the command line is equivalent to specifying the packed attribute on all enum definitions.

In the following example struct my_packed_struct’s members are packed closely together, but the internal layout of its s member is not packed—to do that, struct my_unpacked_struct needs to be packed too.

struct my_unpacked_struct
 {
    char c;
    int i;
 };

struct __attribute__ ((__packed__)) my_packed_struct
  {
     char c;
     int  i;
     struct my_unpacked_struct s;
  };

简单看了个大概,还是百度了牛人精炼解释

其实就是:告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐。

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

__attribute__ 书写特征是:__attribute__ 前后都有两个下划线,并且后面会紧跟一对原括弧,括弧里面是相应的__attribute__ 参数。__attribute__ 语法格式为:__attribute__ ((attribute-list))

其实本人也没有真正理解他,因为项目中用的比较少,更多的还需要去看一些源码了解真正的内涵。

根据结构定义的描述,修改了下定义,就是吧__attribute__((packed)) 放在结构体名称前,然后编译成功解决此问题

typedef struct {
    int32_t mmap_addr;
    char tag[4]; /* 'P', 'R', 'E', ' ' */
} __attribute__((packed)) prelink_info_t ;

至此问题解决

附一个gnu的链接,与大家一起学习提高,搞这些玩意的都是老外,还是努力看英文原文,翻译过来必然会变味不少,现在谷歌浏览器可以翻译整个页面,能看个大概,对比学习还是很方便的,日积月累,看的相关的英文多了,对于看技术资料、处理编译错误也很有帮助的。

https://gcc.gnu.org/onlinedocs/gcc/

猜你喜欢

转载自blog.csdn.net/weixin_35933684/article/details/100706328