I’ve seen countless questions of the form “I don’t like padding how do I turn it off”, but have yet to find anything about forcing the compiler to provide extra padding.
The specific case that I have looks like
struct particle{
vect2 s;
vect2 v;
int rX;
int rY;
double mass;
int boxNum;
};
Where vect2 is a simple struct {double x; double y;} vect2. In order to use SSE2, I need to be able to load a pair of doubles, aligned to 16 byte boundaries. This used to work, until I added the extra int, pushing my struct size from 48 bytes to 56 bytes. The result is segfaults.
Is there some kind of compiler directive I can use that either says “pad this struct to make it a multiple of 16 bytes long”, or “this struct has an alignment of 16-bytes”? I know I could do it manually (tacking on an extra char[12], for example), but I’d really rather just tell the compiler(GCC, preferably ICC compatible), and not have to do it manually if I change the struct in future.
I’m adding my own answer to this, in case someone comes looking for a solution. Mark’s solution is a neat one, and fulfills the automatic requirement, but it is not when I ended up going with. I wanted to avoid this, which is why I asked the question, but there is a “trivial” solution:
By manually checking the current size of the
struct, you can add an appropriate number of chars, (or anything else, butchar‘s let you do it in bytes), to make it the right size. This showed the best performance, as well as simplicity, even though it does require updating every time the struct changes. In this case that is fine, although if you had a struct that could change size depending on options, that would be problematic.Note that my
structwas 56 bytes, and I added 12 to make it 64. That math doesn’t work, because the trailingintwas already being padded out by 4 bytes to the 8-byte boundary; thestructwas actually only 52 bytes before. Adding only 5chars would have worked, by making thestruct57 bytes long, which would have been padded out to 64, but that is not as nice a solution, which is why I used 12 to make it work out exactly.