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

我倾向于使用GCC __packed__ 属性 将Bitfields打包到一个联盟中,然后将它们作为一个 unsigned char (即键入),用于发送SPI或I2C。这种行为都是由我的实施来定义的,并且运作良好。我更喜欢这个掩盖和移动一百层左右的行::)

我的问题是:在那里 __packed__ 下面代码中的属性是多余的?乍一看,我认为可以分配顶级工会成员的人,但我不确定。还是我可以把那些放在嵌套结构中?

// 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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top