【发布时间】:2017-12-27 14:53:50
【问题描述】:
我正在使用 g++ (GCC) 4.7.2.20121109,我想要一个与位边界对齐的嵌套结构。举个例子吧:
#include <iostream>
using namespace std;
typedef struct {
unsigned int a : 1;
unsigned int b : 7;
} __attribute__( ( packed ) ) myType1;
typedef struct {
unsigned int a : 1;
struct {
unsigned int b : 7;
} __attribute__( ( packed ) );
} __attribute__( ( packed ) ) myType2;
int main(void)
{
cout << "sizeof( myType1 ) = " << sizeof( myType1 ) << endl;
cout << "sizeof( myType2 ) = " << sizeof( myType2 ) << endl;
}
用“g++ filename.cpp -o output”编译,给我:
sizeof( myType1 ) = 1
sizeof( myType2 ) = 2
myType1 具有我期望的大小,但 myType2 没有。我希望 sizeof(myType2) 是 1 而不是 2。这可能吗?
【问题讨论】:
-
不是专家,但我认为这是不可能的,因为即使
myType2的内部结构是匿名的,它仍然是一个结构,所以你需要能够解决它,并且因此它至少需要与sizeof(char)对齐。 -
嵌套结构不再是位域,应该遵循对齐要求。所以,我不认为这是可能的。顺便说一句,您不需要嵌套结构上的属性。
-
@Serge 如果我不在嵌套结构中使用
__attribute__( ( packed ) ),则 sizeof 是 5 而不是 2。 -
嗯,那么 gcc 文档不正确 :(
-
您可以使用 -Wpadding 来查看编译器在做什么(clang++ 比 g++ 更冗长)。使用 -Wpedantic 编译器抱怨匿名结构是 GNU 扩展。关于结构填充的一个很好的参考是 catb.org/esr/structure-packing 。但是,所描述的行为对我来说仍然是个谜。