gpt4 book ai didi

c - 冗余 __packed__ 属性

转载 作者:行者123 更新时间:2023-12-02 02:31:43 31 4
gpt4 key购买 nike

此代码适用于 Microchip 的 PIC32MX 微处理器。他们的编译器本质上是 GCC 3.4。

我倾向于使用 GCC 的 __packed__ attribute将位域打包到一个 union 中,然后将它们检索为 unsigned char(即类型双关)以通过 SPI 或 I2C 发送。此行为全部由我的实现定义,并且运行良好。比起一百多行掩码和移位,我更喜欢这个 :)

我的问题是:下面的代码中是否有多余的 __packed__ 属性?乍一看,我认为可以省去那些高层 union 成员,但我不太确定。或者我可以省略嵌套结构中的那些吗?

// Remember that bitfields cannot straddle word boundaries!
typedef struct
{
/// Some flag #1
unsigned FlagOne : 1 __attribute__((packed));
/// Some flag #2
unsigned FlagTwo : 1 __attribute__((packed));
/// A chunk of data
unsigned SomeData : 5 __attribute__((packed));

// and so on, maybe up to 32 bits long depending on the destination

} BlobForSomeChip;

/// This kind of type-punning is implementation defined. Read Appendix A (A7, A12) of
/// the MPLAB C Compiler for PIC32 MCUs manual.
typedef union
{
/// Access the members of this union to set flags, etc
BlobForSomeChip blobdata __attribute__((packed));

/// As a byte for sending via SPI, I2C etc
unsigned char bytes[4] __attribute__((packed));

} BlobData;

最佳答案

首先,我推荐使用-Wall编译。

现在:

  1. BlobForSomeChip 结构声明了 7 位。通常情况下,由于对齐,它的长度为 4 个字节,但对于打包属性,它的长度仅为 1 个字节。
  2. unsigned char[4] 无法打包。无论如何,它总是 4 个字节长。

简而言之:

  1. struct BlobForSomeChip = 1 字节
  2. unsigned char[4] = 4 字节
  3. BlobData = 4 字节(其最大成员的大小)。

最后,BlobData 上的打包属性不是必需的。如果使用,GCC 将简单地忽略它们 - 使用 -Wall 查看输出。

关于c - 冗余 __packed__ 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3571456/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com