英文:
Gcc hidden Members in struct
问题
I am working with an embedded device.
I am creating my own "register representation" to learn the process in the C Language.
I do this via structs placed at given locations:
struct myIo {
u32 flagA : 1;
u32 fieldB : 7;
u32 reserved : 24;
u32 regB;
};
struct attribute((section("sec"))) myIo MyIo;
This works just fine and all, but I wonder how I could remove the
reserved
fields without compromising the padding/alignment enforced by the hardware.
My question is:
How could I design a struct with "hidden" fields, that won't show up when I access the struct.
In essence:
MyStruct.reserved = val;
or
val = MyStruct.reserved;
should throw a compiler error and typing
MyIo.
should not bring up "Auto-Complete" options in Eclipse CDT C/C++.
I am using Arm Cross GCC and Eclipse CDT C/C++.
I am good with C-Standard compliant solutions, compiler pragma solutions, and preprocessor solutions.
英文:
Currently, I am working with an embedded device.
I am creating my own "register representation" to learn the process in the C Language.
I do this via structs placed at given locations:
struct myIo {
u32 flagA : 1;
u32 fieldB : 7;
u32 reserved : 24;
u32 regB;
};
struct __attribute__((section("sec"))) myIo MyIo;
This works just fine and all, but I wonder how I could remove the
reserved
fields without compromising the padding/alignment enforced by the hardware.
My question is:
How could I design a struct with "hidden" fields, that won't show up when I access the struct.
In essence:
MyStruct.reserved = val;
or
val = MyStruct.reserved;
should throw a compiler error and typing
MyIo.
should not bring up "Auto-Complete" options in Eclipse CDT C/C++.
I am using Arm Cross GCC and Eclipse CDT C/C++.
I am good with C-Standard compliant solutions, compiler pragma solutions and preprocessor solutions.
答案1
得分: 5
您可以创建一个未命名的位字段:
struct myIo {
u32 flagA : 1;
u32 fieldB : 7;
u32 : 24;
u32 regB;
};
根据C标准中的"结构和联合说明符"第6.7.2.1p12节的规定,允许这种构造:
具有没有声明符但只有一个冒号和宽度的位字段声明表示一个未命名的位字段。特例情况下,宽度为0的位字段结构成员表示不允许将进一步的位字段打包到前一个位字段所放置的单元中,如果有的话。
请注意,在这种情况下,零大小的位字段也可以工作,但这仅因为没有其他位字段跟随它。
英文:
You can create an unnamed bitfield:
struct myIo {
u32 flagA : 1;
u32 fieldB : 7;
u32 : 24;
u32 regB;
};
Such constructs are allowed as per section 6.7.2.1p12 of the C standard regarding "Structure and union specifiers":
> A bit-field declaration with no declarator, but only a colon and a
> width, indicates an unnamed bit-field. <sup>126)</sup> As a special
> case, a bit-field structure member with a width of 0 indicates that no
> further bit-field is to be packed into the unit in which the previous
> bit- field, if any, was placed.
>
> ---
>
> 126 ) An unnamed bit-field structure member is useful for padding to
> conform to externally imposed layouts.
Note that a zero-sized bitfield will also work in this case, but only because no other bitfields follow it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论