GCC:__attribute__和#pragma的对齐设置 [英] GCC: Alignment settings with __attribute__ and #pragma

查看:213
本文介绍了GCC:__attribute__和#pragma的对齐设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将#pragma pack(2)定义为结构属性?

How can I define #pragma pack(2) as a structure attribute?

我已阅读此处,该__attribute__((packed,aligned(4)))大致等于#pragma pack(4).

I've read here that __attribute__((packed,aligned(4))) is roughly equivalent to #pragma pack(4).

但是,如果我尝试使用它(至少使用2而不是4),则会得到不同的结果.示例:

However, if I try to use this (at least with 2 instead of 4), I get different results. Example:

#include <stdio.h>

#pragma pack(push, 2)
struct test1 {
    char a;
    int b;
    short c;
    short d;
};
struct test1 t1;
#pragma pack(pop)

struct test2 {
    char a;
    int b;
    short c;
    short d;
} __attribute__((packed,aligned(2)));
struct test2 t2;


#define test(s,m) printf(#s"::"#m" @ 0x%04x\n", (unsigned int ((char*)&(s.m) - (char*)&(s)))
#define structtest(s) printf("sizeof("#s")=%lu\n", (unsigned long)(sizeof(s)))

int main(int argc, char **argv) {
    structtest(t1);
    test(t1,a);
    test(t1,b);
    test(t1,c);
    test(t1,d);

    structtest(t2);
    test(t2,a);
    test(t2,b);
    test(t2,c);
    test(t2,d);
}

输出为(在x86或x86x64上编译,Linux,gcc 4.8.4):

Output is (compilation on x86 or x86x64, Linux, gcc 4.8.4):

sizeof(t1)=10
t1::a @ 0x0000
t1::b @ 0x0002
t1::c @ 0x0006
t1::d @ 0x0008
sizeof(t2)=10
t2::a @ 0x0000
t2::b @ 0x0001
t2::c @ 0x0005
t2::d @ 0x0007

b,c和d成员的地址在两种情况下都不相同.

The adresses of members b, c and d are not the same in both cases.

我还要添加另一个__attribute__吗?我什至在gcc文档中找不到关于这些属性的详尽文档.

Is there another __attribute__ I have to add? I can't even find a fine granular documentation on these attributes in the gcc documentation.

推荐答案

如@Nominal Animal在评论中所述,解决方案是将__attribute__((__aligned__(s)))添加到每个struct成员,因为它可用于分别为每个struct设置对齐方式成员.

As noted by @Nominal Animal in the comments the solution is to add __attribute__((__aligned__(s))) to each struct member as it can be used to set the alignment individually for each member.

这篇关于GCC:__attribute__和#pragma的对齐设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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