问题
I am working with some packet data. I have created structs to hold the packet data. These structs have been generated by python for a specific networking protocol.
The issue is that due to the fact that the compiler aligns the structures, when I send the data via the networking protocol, the message ends up being longer than I would like. This causes the other device to not recognize the command.
Does anyone know possible a work around this so that my packers are exactly the size the struct should be or is there a way I can turn off memory alignment?
回答1:
In GCC, you can use __attribute__((packed))
. These days GCC supports #pragma pack
, too.
- attribute documentation
- #pragma pack documentation
Examples:
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
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
来源:https://stackoverflow.com/questions/18341540/no-memory-alignment-with-gcc