没有与 GCC 内存对齐

2024-02-04

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

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

有谁知道可以解决这个问题,以便我的打包程序恰好是结构应有的大小,或者有没有办法可以关闭内存对齐?


在海湾合作委员会,你可以使用__attribute__((packed))。这些天GCC支持#pragma pack, too.

  1. attribute文档 http://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
  2. #pragma pack文档 http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html

例子:

  1. attribute method:

    #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;
    }
    

    Output:

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

    #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;
    }
    

    Output:

    $ make example && ./example
    cc     example.c   -o example
    Packed:     5
    Not Packed: 8
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

没有与 GCC 内存对齐 的相关文章

随机推荐