-
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 && ./example cc example.c -o example Packed: 5 Not Packed: 8
-
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 && ./example cc example.c -o example Packed: 5 Not Packed: 8 Add-fpack-structto 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.
- 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.
结构体内存对齐技巧
本文介绍了使用GCC编译器时如何通过属性和预处理器指令控制结构体成员的内存对齐方式,包括使用__attribute__((packed))和#pragmapack来减少结构体的大小,以及如何使用-fpack-struct选项进一步定制对齐策略。
6万+

被折叠的 条评论
为什么被折叠?



