【问题标题】:How to tell gcc to disable padding inside struct? [duplicate]如何告诉 gcc 禁用结构内的填充? [复制]
【发布时间】:2017-03-31 06:41:49
【问题描述】:

我不确定这是正常现象还是编译器错误,但我有一个包含很多成员的 C 结构。其中,有:

struct list {
    ...  
    ...
    const unsigned char nop=0x90; // 27 bytes since the begining of the structure
    const unsigned char jump=0xeb; // 28 bytes since the begining of the structure
    const unsigned char hlt=0xf4; // 29 bytes since the begining of the structure
    unsigned __int128 i=0xeb90eb90eb90eb90f4f4 // should start at the 30th byte, but get aligned on a 16 byte boundary and starts on the 32th byte instead
    const unsigned char data=0x66; // should start at the 46th byte, but start on the 48th instead.
}; // end of struct list.

我很难找出为什么我的程序无法运行,但我终于发现 hlt 和 i 之间有 2 个字节的间隙,设置为 0x0。这意味着 i 正在对齐。
当我 printf 结构的那部分时,这一点非常清楚,因为使用:

for(int i=28;i<35;i++)
    printf("%02hhX",buf[i]);

我在屏幕上看到EBF40000EB90EB90。

我在我的程序中尝试了volatile struct list data;之类的东西,但它并没有改变对齐问题。

那么是否有#pragma 或__attribute__ 来告诉gcc 不要在struct listtype 中对齐i?

【问题讨论】:

  • 对我来说这看起来像是一个语法错误。这是 C++ 还是什么?
  • 这不是错误。在 C 中,每个结构成员后面都可以有未指定的填充。为什么会出现这个问题?
  • XY 问题。 为什么你要打包struct?如果这是用于存储或序列化:定义帧格式并使用移位进行序列化。
  • 这绝不是stackoverflow.com/questions/2554229/…投票重新开放的副本。

标签: c gcc x86-64 padding gcc6


【解决方案1】:

在 GCC 中,您可以像这样使用 __attribute__((packed)):

// sizeof(x) == 8
struct x
{
    char x;
    int a;
};

// sizeof(y) == 5
struct y
{
    char x;
    int a;
} __attribute__((packed));

见doc。

此外,如果您依赖结构字段的地址,请查看offsetof 宏。也许你根本不需要打包结构。

【讨论】:

  • @MichaelPetch :终于找到了问题:属性是我的语言中的正确拼写。对于这个自动拼写检查错误,我们深表歉意。
【解决方案2】:

@Banex 提到过

#pragma pack(push,1)
struct
{
        char a;
        int b;
        long long c;
} foo;
#pragma pack(pop)

#pragma pack(push,1)内部推送当前打包模式,设置packing为1,无填充

#pragma pack(pop)恢复之前的打包

据说兼容微软的语法

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

【讨论】:

    【解决方案3】:

    struct 中的字段以实现定义的方式填充。

    话虽如此,字段通常在offest 上对齐,offest 是相关数据成员(或数组元素,如果成员是数组)大小的倍数。因此 16 位字段从 2 字节偏移开始,32 位字段从 4 字节偏移开始,依此类推。

    如果您重新排列 struct 中的字段以遵守此准则,您通常可以避免在 struct 中使用任何内部填充(尽管您最终可能会有一些尾随填充)。

    通过将字段放置在适当的偏移量处,可以比强制打包struct 获得性能提升。

    更多详情请见this article on structure packing。

    虽然不能保证使用上述技术,但它们往往在大多数情况下都有效。

    【讨论】:

    • 我从 OPs 问题中的用法怀疑重新排序不是一个有效的选项,因为他使用结构来存储机器指令。在他的情况下,直接启用打包(到 1 个字节)是恕我直言的最佳选择。
    • @MichaelPetch :是的,我的结构的目的是让icrossing 32 字节边界。
    猜你喜欢
    • 1970-01-01
    • 2020-02-03
    • 2015-07-02
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2015-05-22
    • 2010-10-24
    相关资源
    最近更新 更多