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

修改一个项目上的编译告警,出现了'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/

关注微信公众号【嵌入式C部落】,获取更多精华文章,海量编程资料,让我们一起进步,一起成长

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值