This code is for Microchip's PIC32MX microprocessor. Their compiler is essentially GCC 3.4.
I tend use GCC's __packed__
attribute to pack bitfields into a union, and later retrieve them as an unsigned char
(ie. type-punning) for sending over SPI or I2C. This behaviour is all defined by my implementation, and works perfectly. I prefer this to a hundred or so lines of masking and shifting :)
My question is: are there __packed__
attributes in the code below that are redundant? At first glance, I would think that those on the top-level union members can be dispensed with, but I'm not so sure. Or can I leave out those in the nested struct?
// 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;