|
发表于 2014-7-18 15:18:30
|
显示全部楼层
本帖最后由 xf331785508 于 2014-7-18 15:21 编辑
Comparisons of an unpacked struct, a __packed struct, and a struct with individually __packed fields, and of a __packed struct and a #pragma packed struct
ARM Compiler toolchain v5.02 for µVision Using the Compiler
Home > Compiler Coding Practices > Comparisons of an unpacked struct, a __packed struct, and a struct with individually __packed fields, and of a __packed struct and a #pragma packed struct
Comparisons of an unpacked struct, a __packed struct, and a struct with individually __packed fields, and of a __packed struct and a #pragma packed struct
These comparisons illustrate the differences between the methods of packing structures.
Comparison of an unpacked struct, a __packed struct, and a struct with individually __packed fields
The differences between not packing a struct, packing an entire struct, and packing individual fields of a struct are illustrated by the three implementations of a struct shown in Table 12.
Table 12. C code for an unpacked struct, a packed struct, and a struct with individually packed fields
- //Unpacked struct
- struct foo
- {
- char one;
- short two;
- char three;
- int four;
- } c;
- //__packed struct
- __packed struct foo
- {
- char one;
- short two;
- char three;
- int four;
- } c;
- //__packed fields
- struct foo
- {
- char one;
- __packed short two;
- char three;
- int four;
- } c;
-
复制代码
In the first implementation, the struct is not packed. In the second implementation, the entire structure is qualified as __packed. In the third implementation, the __packed attribute is removed from the structure and the individual field that is not naturally aligned is declared as __packed.
Table 13 shows the corresponding disassembly of the machine code produced by the compiler for each of the sample implementations of Table 12, where the C code for each implementation has been compiled using the option -O2.
Table 13. Disassembly for an unpacked struct, a packed struct, and a struct with individually packed fields
- Unpacked struct
- ; r0 contains address of c
- ; char one
- LDRB r1, [r0, #0]
- ; short two
- LDRSH r2, [r0, #2]
- ; char three
- LDRB r3, [r0, #4]
- ; int four
- LDR r12, [r0, #8]
- __packed struct
- ; r0 contains address of c
- ; char one
- LDRB r1, [r0, #0]
- ; short two
- LDRB r2, [r0, #1]
- LDRSB r12, [r0, #2]
- ORR r2, r12, r2, LSL #8
- ; char three
- LDRB r3, [r0, #3]
- ; int four
- ADD r0, r0, #4
- BL __aeabi_uread4
- __packed fields
- ; r0 contains address of c
- ; char one
- LDRB r1, [r0, #0]
- ; short two
- LDRB r2, [r0, #1]
- LDRSB r12, [r0, #2]
- ORR r2, r12, r2, LSL #8
- ; char three
- LDRB r3, [r0, #3]
- ; int four
- LDR r12, [r0, #4]
复制代码
|
|