Visual C++ equivalent of GCC's __attribute__ ((__packed__))

Malkocoglu picture Malkocoglu · Oct 8, 2009 · Viewed 69.9k times · Source

For some compilers, there is a packing specifier for structs, for example ::

RealView ARM compiler has "__packed"
Gnu C Compiler has "__attribute__ ((__packed__))"
Visual C++ has no equivalent, it only has the "#pragma pack(1)"

I need something that I can put into the struct definition.

Any info/hack/suggestion ? TIA...

Answer

Steph picture Steph · Jul 22, 2010

You can define PACK like as follows for GNU GCC and MSVC:

#ifdef __GNUC__
#define PACK( __Declaration__ ) __Declaration__ __attribute__((__packed__))
#endif

#ifdef _MSC_VER
#define PACK( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop))
#endif

And use it like this:

PACK(struct myStruct
{
    int a;
    int b;
});