这段代码是为Microchip的PIC32MX微处理器编写的。他们的编译器本质上是GCC 3.4。
我倾向于使用GCC的__packed__ attribute将位域打包到一个联合中,然后将它们作为unsigned char (即.输入双关语),用于通过SPI或I2C发送。这种行为都是由我的实现定义的,并且工作得很完美。我更喜欢这样做,而不是100行左右的掩码和移位:)
我的问题是:下面的代码中是否有多余的__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;发布于 2010-08-26 10:00:21
首先,我建议使用-Wall进行编译。
现在:
BlobForSomeChip结构声明了7位。通常,由于对齐的原因,它将是4字节长,但对于压缩属性,它将只有1字节长。unsigned char[4]不能打包。无论如何,它始终是4字节长。简而言之:
struct BlobForSomeChip =1 byteunsigned char[4] =4 bytesBlobData =4字节(其最大成员的大小)。结论是,BlobData上的打包属性不是必需的。如果使用了,GCC将直接忽略它们--使用-Wall查看输出。
https://stackoverflow.com/questions/3571456
复制相似问题