visual-c++alignmentpadding

Why #pragma pack in VC++ uses a stack?


I read this article in msdn and I'm wondering why there is an internal compiler stack holding the aligment? I mean there are only 5 values that can be set as packing alignment why would you like to store them? There is even an option to assign an identifier. Why would you ever do that? Just curious.


Solution

  • Headers. Consider the following .cpp file:

    #pragma pack(16)
    #include <stdlib.h>
    

    The <stdlib.h> header defines types that would be affected by the #pragma pack, and the #pragma pack would break the definitions of those types, causing undefined behavior and difficult-to-diagnose runtime errors.

    We defend against this in <stdlib.h> by pushing the packing, resetting it to a well-known packing, and popping the original packing back at the end of the file. Headers for other libraries and SDK could do something similar to defend against this scenario.