问题描述
我想知道是否有 GCC C 编译器指令允许我确定结构打包的位顺序?喜欢的东西:
I was wondering if there is a GCC C Compiler directive that allows me to determine the bit order for packing of a structure? Something to the likes of:
#pragma bit_order left
这种需求的基本原理是我有以下结构:
The rationale for such a need is that I have the following structure:
struct {
union {
unsigned char BYTE;
struct {
unsigned char B0: 1;
unsigned char B1: 1;
unsigned char B2: 1;
unsigned char B3: 1;
unsigned char B4: 4;
}BIT;
}ITEM;
} myStruct;
有了这个结构,我希望编译器这样打包:
With this structure, I would like the compiler to pack it this way:
Bit order: | 7 6 5 4 3 2 1 0 |
Label: |B0 B1 B2 B3 B4 B5 B6 B7 |
而不是 GCC 是怎么做的:
Rather than how GCC does it:
Bit order: | 7 6 5 4 3 2 1 0 |
Label: |B7 B6 B5 B4 B3 B2 B1 B0 |
我正在处理具有巨大头文件的 MCU,这些头文件具有根据规定的硬件地址计算位偏移的结构.我希望 GCC C 编译器中有一个编译器指令可以在我尝试翻转制造商提供的文件中的所有字段之前为我进行位顺序交换.
I am dealing with MCUs that have huge header files that have structures that compute bit offsets according to stipulated hardware addresses. I am hoping that there is a compiler directive in GCC C Compiler that does the bit order swap for me before I attempt the flip all the fields in the manufacturer supplied file.
推荐答案
您使用的是哪个版本的 GCC 以及哪个平台?存在一个 pragma 可以解决问题,但它不适用于从 GCC 4 开始的 x86.
Which version of GCC are you using and which platform? A pragma exists that may do the trick, but it doesn't work on x86 starting with GCC 4.
#pragma reverse_bitfields on
更多详情请访问:
http://groups.google.com/group/gnu.gcc.help/browse_thread/thread/747918655affa5c0?pli=1
如果您不介意重新构建 GCC,所有相关的构建设置都在这里(搜索 bitfield
):
If you don't mind rebuilding GCC, all the relevant build settings are here (search for bitfield
):
http://gcc.gnu.org/onlinedocs/gccint/Storage-布局.html
关于位域不好的一些细节:
Some details about bitfields being bad:
这篇关于如何使用 GCC 编译器强制执行 struct 位顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!