gccvisual-c++alignment

GCC vs MSVC class packing and alignment


Is there a way with compiler flags to create the same memory layout of a base class and a derived class under msvc compared to its equivalent in gcc? Im using VS2010 and comparing it to GCC 4.1.1

So

#if define _MSVC
// window 
DALIGN(A,B) __declspec(align(A)) B
#else
// GCC
DALIGN(A,B) B __attribute__((aligned(A)))
#endif
class A
{ 
  DALIGN(CVector V,16);
  int a;
}
class B : public A
{
  int b;
}

A is 16byte aligned making it 0x20(32) B is also 16 byte aligned, but is either also 0x20(32) on GCC but on msvc it is 0x30(48)

is there a way to force the msvc to pack the data like GCC is?

Reason for this: I create data and load it directly into the classes on different platforms. What would really be nice is if I could use the exact same data layout on both platforms. (Yes endian is the same on both platforms)


Solution

  • Adding #pragma pack(push, 4) / #pragma pack(pop) around the class A and class B succeeded in correctly aligning the data as GCC aligns it.

    Note that if the inheritance is extended, it seems like for any required aligned class and forward through the inheritance all require the packing. Example classes A,B,C,D,E,F C has aligned members C,D,E,F all require the packs around them.