2

如何在 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 不对齐该结构?

4

3 回答 3

6

不,它不能完成。

您显示的结构的最小大小是 8*4 = 32 字节。

sizeof(unsigned long) = 8 在 64 位架构 (Linux)

编辑:如果你会使用

-unsigned而不是unsigned long

或者

  • uint32_tuint64_t不是unsigned longunsigned long long

你会得到预期的对齐。

于 2011-02-03T08:07:05.583 回答
2

#pragma pack(x) 可以更改 GCC 和 MSVC 的结构对齐限制。

GCC 使用 LP64 模型进行 64 位构建——这意味着 long 和指针是 64 位的。您需要将 32 位字段更改为 unsigned int,或者使用 uint32_t 和 uint64_t 以获得稳定的字段大小。

#pragma pack(1)

typedef struct{
  unsigned long long offset;
  unsigned long long size;
  unsigned int type;
  unsigned int acpi;
}memstruct;

#pragma pack()
于 2011-02-03T08:11:40.457 回答
1

这是使用 gcc 控制对齐的一个选项:

http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html

于 2011-02-03T08:09:30.573 回答