3

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

我倾向于使用 GCC 的__packed__属性将位域打包到一个联合中,然后将它们检索为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;
4

1 回答 1

2

首先,我建议使用-Wall.

现在:

  1. BlobForSomeChip结构声明了 7 位。通常,由于对齐,它的长度为 4 个字节,但对于打包属性,它只有 1 个字节长。
  2. Aunsigned char[4]不能打包。无论如何,它总是 4 个字节长。

简而言之:

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

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

于 2010-08-26T02:00:21.290 回答