首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >冗余__packed__属性

冗余__packed__属性
EN

Stack Overflow用户
提问于 2010-08-26 09:27:21
回答 1查看 1.2K关注 0票数 3

这段代码是为Microchip的PIC32MX微处理器编写的。他们的编译器本质上是GCC 3.4。

我倾向于使用GCC的__packed__ attribute将位域打包到一个联合中,然后将它们作为unsigned char (即.输入双关语),用于通过SPI或I2C发送。这种行为都是由我的实现定义的,并且工作得很完美。我更喜欢这样做,而不是100行左右的掩码和移位:)

我的问题是:下面的代码中是否有多余的__packed__属性?乍一看,我会认为那些顶级工会成员可以被免去,但我不是很确定。或者我可以省略嵌套结构中的那些?

代码语言:javascript
复制
// 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;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-08-26 10:00:21

首先,我建议使用-Wall进行编译。

现在:

  1. BlobForSomeChip结构声明了7位。通常,由于对齐的原因,它将是4字节长,但对于压缩属性,它将只有1字节长。
  2. A unsigned char[4]不能打包。无论如何,它始终是4字节长。

简而言之:

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

结论是,BlobData上的打包属性不是必需的。如果使用了,GCC将直接忽略它们--使用-Wall查看输出。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3571456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档