如何告诉gcc禁用结构内部的填充? [英] How to tell gcc to disable padding inside struct?

查看:93
本文介绍了如何告诉gcc禁用结构内部的填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这是正常的还是编译器的错误,但是我有很多成员的C结构.其中有:

I’m unsure on whether it’s normal or it’s a compiler bug but I have a C struct with lot of members. Among of them, there’s, :

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.

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

I had a hard time to find out why my program wasn’t working, but I finally found there’s a 2 bytes gap between hltand i which is set to 0x0. This means that the i is getting aligned.
This is very clear when I printf that part of the structure, because with :

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

我在屏幕上看到EBF40000EB90EB90.

我在程序中尝试了类似volatile struct list data;的操作,但是并没有改变对齐问题.

I tried things like volatile struct list data;in my program, but it didn’t changed the alignment problem.

那么有没有#pragma__attribute__告诉gcc在struct list类型内不对齐i?

So is there a #pragma or a __attribute__to tell gcc to not align i inside struct listtype ?

推荐答案

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

In GCC you can use __attribute__((packed)) like this:

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

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

请参见文档.

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

Also if you rely on the addresses of struct fields, take a look at the offsetof macro. Maybe you don't need to pack the structure at all.

这篇关于如何告诉gcc禁用结构内部的填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆