简体   繁体   English

我是否误解了GCC中的__attribute __((包装))?

[英]Am I misunderstanding __attribute__ ((packed)) in GCC?

I am trying the following, with gcc on win32. 我正在尝试以下方法,在Win32上使用gcc。

#include <stdio.h>

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

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

I would expect that the printed value is 5, but it's 8. 我希望打印的值是5,但它是8。

With the following, however, I get 5. 但是,有了以下内容,我得到了5。

#include <stdio.h>

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

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

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. 我已经阅读了gcc的手册以及关于此的几个问题,但我仍然感到困惑。 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. 同样从关于SO的这些问题的答案中,我了解到我不应该使用打包结构进行编组 ,也许我不会使用太多,但是我仍然想了解我在这种情况下看不到的内容。简短的节目。

Note: the problem occurs with both gcc-4.9.2 and gcc-4.8.4. 注意:gcc-4.9.2和gcc-4.8.4都会出现此问题。

You have the attribute in the wrong place - try this: 您将属性放在错误的位置-尝试以下操作:

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

As per the example in the gcc manual, this will cause x to be packed such that it immediately follows c . 按照gcc手册中的示例,这将导致x被打包,使其紧随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. 当然,您首先不应该这样做,因为您的代码将在某些架构上中断,即使不中断,也可能会导致性能下降。

Working fine on my environment Centos 5.11 (64bit) prints 5 for the first case you mentioned. 在我的环境中可以正常工作Centos 5.11(64位)会为您提到的第一种情况打印5。

gcc version 4.9.1 (GCC) gcc版本4.9.1(GCC)

gcc file.c gcc file.c

./a.out 

5 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM