GCC隐式对齐问题。 (64 位代码)
如何在 gcc 中显式禁用已定义变量的对齐?
采用这段代码:
typedef struct{
unsigned long long offset;
unsigned long long size;
unsigned long type;
unsigned long acpi;
}memstruct;
memstruct *memstrx;
这将定义一个大小为 24 字节的结构。
我尝试这样做:
memstrx=(void*)(0x502);
所以&memstrx[0]
的值应为 0x502&memstrx[1]
, 0x51A&memstrx[2]
, 0x532
...等等等等。
但事情似乎不太对劲。
相反,&memstrx[1]
,显示地址 0x522&memstrx[2]
, 0x542&memstrx[3]
,0x552
...等等。
我怀疑 GCC 已隐式地将结构大小重新调整为 32 字节(从 24 字节),强制执行(每个条目的 64 位对齐)。我真的不希望这种行为只针对这种结构。我应该如何告诉 GCC 不要调整该结构?
How can I explicitly disable alignment on defined variable in gcc?
Take this code:
typedef struct{
unsigned long long offset;
unsigned long long size;
unsigned long type;
unsigned long acpi;
}memstruct;
memstruct *memstrx;
This would define an structure having a size of 24 bytes.
I tried doing:
memstrx=(void*)(0x502);
So
&memstrx[0]
should have an value of 0x502&memstrx[1]
, 0x51A&memstrx[2]
, 0x532
... and so on and so forth.
But things doesn't seem to be right.
Instead, the
&memstrx[1]
, displays an address of 0x522&memstrx[2]
, 0x542&memstrx[3]
, 0x552
... and so on and so forth.
I suspect GCC has implicitly re-sized the structure to 32 bytes (from 24 bytes), forcing a (64-bit alignment of each entry). And I don't really want this behavior only for this structure. How should I tell GCC to not align that structure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这是不可能的。
您显示的结构的最小大小是 8*4 = 32 字节。
sizeof(unsigned long) = 8(64 位体系结构 (Linux))
编辑: 如果您要使用
-
unsigned
而不是unsigned long
或
uint32_t
和uint64_t
而不是unsigned long
和unsigned long long
您将获得预期的对齐方式。
No it can't be done.
The minimal size of the structure you show is 8*4 = 32 bytes.
sizeof(unsigned long) = 8 on 64 bit architecture (Linux)
Edit: if you would use
-
unsigned
instead ofunsigned long
or
uint32_t
anduint64_t
instead ofunsigned long
andunsigned long long
you would get expected alignment.
#pragma pack(x) 可以更改 GCC 和 MSVC 上的结构对齐限制。
GCC 使用 LP64 模型进行 64 位构建 - 这意味着长整型和指针是 64 位。您需要将 32 位字段更改为 unsigned int,或者使用 uint32_t 和 uint64_t 以获得稳定的字段大小。
#pragma pack(x) can change the structure alignment restrictions on both GCC and MSVC.
GCC uses the LP64 model for 64bit builds - which means longs and pointers are 64bits. You need to change to unsigned int for your 32bit fields, OR use and uint32_t and uint64_t for stable field sizes.
这里有一个使用 gcc 控制对齐的选项:
http://gcc.gnu.org/ onlinedocs/gcc/Structure_002dPacking-Pragmas.html
here's one option to control alignment using gcc:
http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html