We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
I'm using the Keil uVision3. How do I pack structs?
Do I use __packed or is there a pragma?
is this correct? it doesn't compile...
typedef struct { UINT8 key_diff; UINT8 key_state; } __packed SCmd_KeyPress;
I'll give you a real example.
That's actually just an example of what one should not do with C data structures structs. C structs have no business being copied or used outside the internals of a C program. You haven't demonstrated a problem with struct packing, but one with the design of that program.
The most common - and probably the only valid reason - for packing structures is to save space when doing embedded work. It is a trade-off between data size and code size, and often also a trade-off in speed.
If you need to work with hardware, or write data to a file or build packets for transfer over a network, you should instead byte-pack your data yourself, similar to:
pos = packet.data; pos = insert_u8(pos,my_8bit_value); pos = insert_u16(pos,my_16bit_value); ... assert(pos - packet.data == expected_packet_size);
The reason for this is that when permanently storing information, or accessing hardware or communicating, you have more things to take into account. A packed structure will just save you the extra space between individual members, but may still have the incorrect byte order.