I have recently come across this #pragma pack(1) preprocessor directive and was wondering why it is being used?
I Googled the usage, and found it has other options such as push,pop etc. Has anyone used this on their embedded application?
I would like to know some examples of how/why you have used this directive and on what kind of processor? What are the pro's/con's of using this directive?
#pragma pack(1)ensures that C
structitems are packed in order and on byte boundaries. It may save RAM - which is often precious in a microcontroller.
Packed structs also allow for casting directly over memory buffers for data interchange:
Be careful where you use
#pragma pack. It's globally scoped (as it's in the preprocessor), so forgetting to turn it off will affect any
#includefiles. If you only mean to pack certain structs, consider using GCC's
However, due to alignment issues, packed structs can impact performance. For example:
When packed into bytes:
Will be stored as (not accounting for endianness):
a, b0, b1, b2, b3, c, d
However, many architectures require 32bit accesses to be aligned to 32bit addresses. With the packed struct, the machine will have to make several byte accesses then stich them together again.
Faced with the above
structwithout packing enabled, the compiler could reorganise it as:
b0, b1, b2, b3, a, c, d