我是否误解了GCC中的__attribute __((包装))? [英] Am I misunderstanding __attribute__ ((packed)) in GCC?

查看:63
本文介绍了我是否误解了GCC中的__attribute __((包装))?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Win32上的gcc尝试以下操作.

I am trying the following, with gcc on win32.

#include <stdio.h>

struct st { char c; int x; } __attribute__ ((packed));

int main() {
    printf("%d\n", sizeof(struct st));
    return 0;
}

我希望打印的值是5,但它是8.

I would expect that the printed value is 5, but it's 8.

但是,通过以下操作,我得到了5.

With the following, however, I get 5.

#include <stdio.h>

#pragma pack(1)
struct st { char c; int x; };

int main() {
    printf("%d\n", sizeof(struct st));
    return 0;
}

程序中肯定有问题,但是我看不到什么.我已经阅读了 gcc的手册和一些有关因此,我仍然感到困惑.有提示吗?

There must be something wrong in my program, but I can't see what. I have read gcc's manual and several questions on SO about this, and I'm still puzzled. Any hint?

同样从这些问题的答案中,我了解到我不应该将打包结构用于

Also from the answers to these questions on SO, I understand that I should not use packed structs for marshalling, and I probably won't use it much, but I still would like to understand what I'm not able to see in such a short program.

注意:gcc-4.9.2和gcc-4.8.4都会出现此问题.

Note: the problem occurs with both gcc-4.9.2 and gcc-4.8.4.

推荐答案

您将属性放置在错误的位置-尝试以下操作:

You have the attribute in the wrong place - try this:

struct st { char c;
            int x __attribute__ ((packed));
          };

按照gcc手册中的示例,这将导致 x 被打包,使其紧随 c .

As per the example in the gcc manual, this will cause x to be packed such that it immediately follows c.

当然,您一开始就不应该这样做,因为您的代码将在某些体系结构上中断,即使不中断,也可能会导致性能下降.

Of course you shouldn't really be doing this in the first place, as your code will break on certain architectures, and even where it doesn't break there may be performance penalties.

这篇关于我是否误解了GCC中的__attribute __((包装))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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