1

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?

Adam Yaxley
  • 670
  • 1
  • 7
  • 13
  • You cannot detect the use of `pragma pack` specifically, but C++11 does have [`alignof()`](https://en.cppreference.com/w/cpp/language/alignof) at least – Remy Lebeau Oct 10 '18 at 02:44
  • Hi @RemyLebeau, thanks for the information. I've created a compile-time check using `alignof` that only seems to fail when `N` is explicitly set for a `#pragma pack(N)` directive, but I can't find any documentation regarding this behavior. Do you know why this might happen? See here: https://godbolt.org/z/d2Y4W9 – Adam Yaxley Oct 10 '18 at 04:26

1 Answers1

3

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).

Finas
  • 136
  • 3
  • 1
    You might change MACRO by (`constexpr`) function/variable. – Jarod42 Oct 10 '18 at 09:53
  • @jarod42: You are right. The constexpr would be the better choice, if available. But some older compiler, supporting c++ 11 do not (MSVC) support it. – Finas Oct 10 '18 at 10:20
  • @Finas: This works well for every packing value except 16 (https://godbolt.org/z/PIxbU2) – Adam Yaxley Oct 19 '18 at 03:21