冗長__packed__属性
-
01-10-2019 - |
質問
このコードは、MicrochipのPIC32MXマイクロプロセッサ用です。彼らのコンパイラは基本的にGCC 3.4です。
GCCを使用する傾向があります __packed__
属性 ビットフィールドを組合に詰めて、後でそれらを 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;
解決
まず、コンパイルをお勧めします -Wall
.
今:
-
BlobForSomeChip
構造体には7ビットが宣言されています。通常、アラインメントのために長さ4バイトになりますが、パックされた属性を使用すると、長さは1バイトしかありません。 - a
unsigned char[4]
梱包できません。何があっても、常に4バイトの長さになります。
要するに:
struct BlobForSomeChip
= 1バイトunsigned char[4]
= 4バイトBlobData
= 4バイト(最大のメンバーのサイズ)。
結論、詰め込まれた属性 BlobData
必要ありません。 GCCは、使用すると単にそれらを無視します - 使用して出力を参照してください -Wall
.
所属していません StackOverflow