No memory alignment with GCC

Source: Internet
Author: User
  1. attributeMethod:

    #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 && ./examplecc     example.c   -o examplePacked:     5Not Packed: 8
  1. pragma packMethod:

    #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 && ./examplecc     example.c   -o examplePacked:     5Not 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-structSwitch causesGccTo 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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.