In C, when we use structures, when would it be inappropriate to use #pragma pack directive..?
an addition to the question…..
Can someone please explain more on how might the accessing of unaligned data specially with a pointer fail?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Firmware developer here.
#pragma packis very familiar territory. I’ll explain.In general you should not use
#pragma pack. Yes, it will make your structures smaller in memory since it eliminates all padding between struct members. But it can make accessing those members much more expensive since the members may no longer fall along their required alignment. For example, in ARM architectures, 4-byte ints are typically required to be 4-byte aligned, but in a packed struct they might not be. That means the compiler needs to add extra instructions to safely access that struct member, or the developer has to access it byte-by-byte and reconstruct the int manually. Either way it results in more code than an aligned access, so your struct ends up smaller but your accessing code potentially ends up slower and larger.You should use
#pragma packwhen your structure must match an exact data layout. This typically happens when you are writing code to match a data transport or access specification… e.g., network protocols, storage protocols, device drivers that access HW registers. In those cases you may need#pragma packto force your structures to match the spec-defined data layout. This will possibly incur the same performance penalty mentioned in the previous paragraph, but may be the only way to comply with the specification.