码迷,mamicode.com
首页 > 其他好文 > 详细

No Memory Alignment with GCC

时间:2014-06-25 07:29:49      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:c

  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
  1. 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
  2. Add -fpack-struct to GCC
    -fpack-struct[=n]
    Without a value specified, pack all structure members together without holes. When a value is specified (which must be a small power of two), pack structuremembers according to this value, representing the maximum alignment (that is, objects with default alignment requirements larger than this will be outputpotentially unaligned at the next fitting location.

    Warning: the -fpack-struct switch causes GCC to generate code that is not binary compatible with code generated without thatswitch. Additionally, it makes the code suboptimal. Use it to conform to a non-default application binary interface.



No Memory Alignment with GCC,布布扣,bubuko.com

No Memory Alignment with GCC

标签:c

原文地址:http://blog.csdn.net/michaelrun/article/details/34120633

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!