[英]Size of packed struct with union of bit fields less than 8 bits in C
Is it possible in C to get the size of the following structure to be 2? 在C中是否可以将以下结构的大小设为2?
#include <stdio.h>
struct union_struct {
char foo;
char bar : 2;
union {
char foobar1 : 6;
char foobar2 : 6;
};
};
int main(void)
{
printf("size of union struct: %d\n", sizeof(struct union_struct));
return 0;
}
output, compiled with gcc: 输出,用gcc编译:
size of union struct: 3
If you are relying on implementation defined behavior, then yes, but you have to organize it a bit differently: 如果您依赖于实现定义的行为,那么是的,但您必须以不同的方式组织它:
#ifdef UNNAMED_BITFIELDS_ARE_WELL_DEFINED
#define ANON
#else
#define ANON3(X) anonymous__## X ##__
#define ANON2(X) ANON3(X)
#define ANON ANON2(__LINE__)
#endif
struct union_struct {
char foo;
union {
struct {
char bar : 2;
char ANON : 6;
};
struct {
char ANON : 2;
char foobar1 : 6;
};
struct {
char ANON : 2;
char foobar2 : 6;
};
};
};
The first byte is foo
, the second byte is the anonymous union. 第一个字节是foo
,第二个字节是匿名联合。 Then anonymous union has 3 single byte anonymous structs. 然后匿名联盟有3个单字节匿名结构。 Each struct (optionally) uses unnamed bit-fields to allow foobar1
and foobar2
to represent the same 6 bits that follow bar
. 每个结构(可选)使用未命名的位字段,以允许foobar1
和foobar2
表示跟随bar
的相同6位。
From my understanding of the C.11 standard the above code is correct when UNNAMED_BITFIELDS_ARE_WELL_DEFINED
is defined. 根据我对C.11标准的理解,当定义UNNAMED_BITFIELDS_ARE_WELL_DEFINED
时,上述代码是正确的。 However, there seems to be debate on whether or not unnamed bit-fields have well-defined semantics (see comments below). 然而,关于未命名的位域是否具有明确定义的语义似乎存在争议(见下面的评论)。 If unnamed bit-fields do not have well-defined semantics, then the code above can expand each ANON
macro into a name for the bit-field. 如果未命名的位字段没有明确定义的语义,则上面的代码可以将每个ANON
宏扩展为位字段的名称。
However, the C.11 standard only defines bit-fields on _Bool
, int
, and unsigned
, while the use of any other type for a bit-field is implementation defined (C.11 §6.7.2.1 ¶5). 但是,C.11标准仅定义_Bool
, int
和unsigned
上的位字段,而位字段的任何其他类型的使用是实现定义的(C.11§6.7.2.1¶5)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.