Find holes in C structs due to alignment

后端 未结 7 2510
难免孤独
难免孤独 2021-02-20 18:26

Is there a way in gcc or clang (or any other compiler) to spit information about whether a struct has holes (memory alignment - wise) in it ?

Thank you.

ps: If

7条回答
  •  感动是毒
    2021-02-20 18:45

    You can detect such "holes" via the offsetof macro:

    #include 
    
    struct test {
      char a;
      int b;
    };
    ...
    printf("%zu", offsetof(struct test, b));
    

    If this prints more than 1, b obviously has alignment requirements and the compiler produces a gap in between.

    Obviously this happens at runtime, not at compile-time, but you can write a script that produces a similar source file, compiles and runs it before the rest of your project, and then, based on the output you do further decisions on how to build your project.

    I don't think any compiler provides a facility to notify you about that.

提交回复
热议问题