Search code examples
c++c++11compile-timepragma-pack

Compile time check for usage of #pragma pack


Most compiliers support changing the packing of a class by using a #pragma pack(N) directive, where N is the new minimum acceptable alignment for each member.

Is it possible to check at compile-time whether or not a #pragma pack(N) has been specified. Additionally, is there a way to determine N?


Solution

  • You cannot test the struct packing directly, instead you have to create a test structure and check its size:

    struct Test_Pack_Struct {
        unsigned char   bVal;
        __int64         lVal;
    };
    #define GetStructPacking()  (sizeof(Test_Pack_Struct)-8)
    

    At compile time you may check the apprriate size with a static assert (requires C++ 11 or higher), for example:

    static_assert( GetStructPacking() == 4, "Error: 4 byte packing assumed" );
    

    At runtime you can assign the value of GetStructPacking macro to a variable or use it in expressions:

    int iPacking = GetStructPacking()
    

    Keep in mind, that the size of the Test_Pack_Struct structure depends on the posistion where it is defined (headers, code files etc).

    A drawback is that, if you want to make several packing checks in the same context, you have to defined different structures (and macros if you want to use it).