c++cvisual-c++gccdata-structures

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


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


Solution

  • 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;
    });