What is the best way to make a non-packed non-padded struct in C or C++? The goal is:
typedef struct {
char first[3]; //padded to 8 because next type has size 8
double second;
char third;
} SomeStruct;
but do something to make sizeof(SomeStruct) be equal 17;
The structure is defined by external library specification. I have a 2 decisions:
1)
#pragma pack (push, 1)
typedef struct {
char first[3];
char unused[5]; // Manual padding of second field.
double second;
char third;
} SomeStruct;
#pragma pack (pop)
2) Using the first variant of declaration, but write (int)(&((SomeStruct*)0)->third) + sizeof(((SomeStruct*)0)->third) instead of sizeof(SomeStruct) when serializing data. I don’t need to serialize arrays of such structs, so can do that.
But both of them are dirty hacks. Is there a standard approach of removing the structs padding in C?
C11 now has the
_Alignaskeyword that could suggest a more narrow alignment of yourdoubleThis would do narrower aligment whenever that is possible, that is if the standard operators for
doubleon your platform are able to cope with such an alignment. (If not you are screwed anyhow.)Clang already implements that feature, and other compilers such as gcc already have extensions that come close to it, so you can easily write yourself a wrapper that uses this syntax and is “future proof”.
Edit: I only saw after posting that your question is also about C++. I think C++1 has the same feature as
alignas. (C11 hasalignas -> _Alignasvia a macro from a standard header file.)