与GCC无内存对齐

时间:2013-08-20 17:36:59

标签: c gcc compiler-construction compiler-optimization memory-alignment

我正在使用一些数据包数据。我创建了用于保存数据包数据的结构。这些结构是由python为特定的网络协议生成的。

问题在于,由于编译器对齐结构这一事实,当我通过网络协议发送数据时,消息最终会比我想要的更长。这会导致其他设备无法识别该命令。

有没有人知道可以解决这个问题,这样我的打包器的大小应该是结构应该的大小,还是有办法可以关闭内存对齐?

1 个答案:

答案 0 :(得分:6)

在GCC中,您可以使用__attribute__((packed))。这些天GCC也支持#pragma pack

  1. attribute documentation
  2. #pragma pack documentation
  3. 示例:

    1. attribute方法:

      #include <stdio.h>
      
      struct packed
      {
          char a;
          int b;
      } __attribute__((packed));
      
      struct not_packed
      {
          char a;
          int b;
      };
      
      int main(void)
      {
          printf("Packed:     %zu\n", sizeof(struct packed));
          printf("Not Packed: %zu\n", sizeof(struct not_packed));
          return 0;
      }
      

      输出:

      $ make example && ./example
      cc     example.c   -o example
      Packed:     5
      Not Packed: 8
      
    2. pragma pack方法:

      #include <stdio.h>
      
      #pragma pack(1)
      struct packed
      {
          char a;
          int b;
      };
      #pragma pack()
      
      struct not_packed
      {
          char a;
          int b;
      };
      
      int main(void)
      {
          printf("Packed:     %zu\n", sizeof(struct packed));
          printf("Not Packed: %zu\n", sizeof(struct not_packed));
          return 0;
      }
      

      输出:

      $ make example && ./example
      cc     example.c   -o example
      Packed:     5
      Not Packed: 8