I would like to create a struct
that has a certain alignment.
I would like to use the same struct definition for both GCC and VisualC++ compilers.
In VisualC++, one typically does this:
__declspec(align(32))
struct MyStruct
{
// ...
};
In GCC, one typically does this:
struct MyStruct
{
// ...
} __attribute__ ((aligned (32)));
I could of course create the appropriate macros to make this work:
BEGIN_ALIGNED_STRUCT(32)
struct
{
// ...
}
END_ALIGNED_STRUCT(32)
;
And thus be able to handle both cases transparently, but here I have to duplicate the alignment constant (32
), which I'd like to avoid.
An alternative in GCC is to put the __attribute__
after the struct tag, as mentioned in the docs, like so:
struct __attribute__ ((aligned (32))) MyStruct
{
// ...
};
And thus I could make this type of syntax work:
ALIGNED_STRUCT(32) MyStruct
{
// ...
};
Does anyone have any better versions? Other ideas?
I tried a little code searching, but didn't find anything too promising.
Update: Based on @John's comment, here's another version that could work (I haven't compiled it, but the docs indicate it's an OK idea)
struct MyStruct_Unaligned
{
// ...
};
TYPEDEF_ALIGNED(32, MyStruct_Unaligned, MyStruct);
// Would expand to one of:
//
// typedef __declspec(align(32)) MyStruct_Unaligned MyStruct;
//
// typedef struct __attribute__ ((aligned (32))) MyStruct_Unaligned MyStruct
See Question&Answers more detail:
os