c - 没有与 GCC 的内存对齐

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

我正在处理一些数据包数据。我已经创建了结构来保存数据包数据。这些结构由 python 为特定的网络协议(protocol)生成。

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

有没有人知道可以解决这个问题,以便我的加壳器恰好是结构应该的大小,或者有什么方法可以关闭内存对齐?

最佳答案

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

  1. attribute documentation
  2. #pragma pack documentation

例子:

  1. 属性方法:

    #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
    

关于c - 没有与 GCC 的内存对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18341540/

相关文章:

c - C语言如何在MPI中调用same rank?

C 段错误

c - 了解 gcc 4.9.2 自动矢量化输出

c - 用于解释器的基于堆栈的 VM 的替代方案

c - C 中的指针赋值、malloc() 和 free()

c++ - 生成文件 : error running 'make all'

c++ - 在 Mac OS X 上以多态方式捕获 -fno-rtti 共享库中的异常

compiler-construction - ANTLR4 中的 EOF 行为

Ruby 到 Actionscript3 字节码

mysql - 多行sql求和;