This thread has been locked.
If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.
Hi,
we have a problem with struct alignment and size when containing 32 bit members on C2000 compiler (6.4.9):
struct
{
int id;
int count_bytes : 8;
int result : 8;
unsigned long number;
int index : 8;
int type : 8;
} serial_data;
sizeof(serial_data) is given as 6 while I would expect 5.
When replacing unsigned long number by 2 ints, the size is correctly given as 5.
Unfortunately, this is a struct describing a serial data stream, so we are not free in chosing the struct elements.
The stuff word is added at the end of the structure. This is correct if the struct is used as array to provide alignment for the next 32 bit number element, but this does not seem to be necessary for a single struct.
Is there some compiler setting that would prevent this alignment at the end?
Regards,
Stephan
As you have mentioned, the existence of the unsigned long means, per ISO C, the sizeof the struct must be a multiple of 2. One reason that C requires this, as you have also mentioned, is that this requirement means that all members in the array will still meet any alignment requirements.
Could there be relaxed rules of instances that are single vs instances that are in an array? Perhaps, but then things like sizeof and pointer math become context sensitive and it would seem quite difficult to pull off. Perhaps anonymous struct types like the one in the example could be treated as a special case since we can't (?) create arrays of them; but looking down the road at language features such as decltype, even this isn't true.
As for any compiler specific extensions, gcc's __attribute__((aligned(1))) __attribute__((__packed__)) might do the trick, but I don't see packed as an extension supported by C2000 CGT.
When a structure is laid out, the compiler must use the most conservative assumptions. In this case, a struct which contains a 32-bit long must be sized as a multiple of 32-bit longs. That is the only way to be sure to cover all possible scenarios. Consider the case where an array of this structure is defined in a separate file.
StephanS said:Is there some compiler setting that would prevent this alignment at the end?
Unfortunately, no.
StephanS said:this is a struct describing a serial data stream, so we are not free in chosing the struct elements.
But reading directly from the serial data stream into a structure is not the only method. You could read 32-bits at a time, then copy the correct bits from each 32-bit chunk into a structure field. I agree this is not as convenient, but it is a common technique.
Thanks and regards,
-George