Hi,
I'm working with at91sam7s256. Of course i'm using Keil. I want to align struct with bitfields one by one because a want to cast buffer on my struct and read data using that struct. the problem is that:
i made struct with attribute packed and then size of this struct is 18 bytes, without attribute packed size struct is 20 bytes, but struct should have got 16 bytes.
Can anyone help me? I dont know how to force Keil to compile this struct in one piece without unused fields betweed struct fields.
Gee - any reason why you didn't see a need to post the struct before asking if anyone can help you? Do you expect us to hack your computer to get access to the source code?
It was a trap for fairy :) Ok, and now seriously. Its a struct i want to use. I need to cast buffer (16 bytes) on this struct and the structure should have 16 bytes but compiler (Keil) returns that the structure have 18 bytes. I checked in Devcpp, the structure have 16 bytes.
struct __attribute__ ((packed)) Structure{ unsigned char field1:2; unsigned char field2:6; unsigned char field3:8; unsigned char field4:8; unsigned char field5:8; unsigned int field6:12; unsigned char field7:4; unsigned char field8:1; unsigned char field9:1; unsigned char field10:1; unsigned char field11:1; unsigned char field12:2; unsigned int field13:12; unsigned char field14:3; unsigned char field15:3; unsigned char field16:3; unsigned char field17:3; unsigned char field18:3; unsigned char field19:1; unsigned char field20:7; unsigned char field21:7; unsigned char field22:1; unsigned char field23:2; unsigned char field24:3; unsigned char field25:4; unsigned char field26:1; unsigned char field27:5; unsigned char field28:1; unsigned char field29:1; unsigned char field30:1; unsigned char field31:1; unsigned char field32:2; unsigned char field33:2; unsigned char field34:7; unsigned char field35:1; };
www.keil.com/.../armccref_babjddhe.htm
the structure should have 16 bytes
No, it shouldn't. You want it to have that size, but there's no particularly compelling reason why this wish should be granted. Bitfields are meant for internal work of a C program, not for duplicating external storage patterns.
The lesson to be learned is: Never make any assumptions about the storage representation of bitfields. Each individual bitfield will hold values within its defined range and signedness. All other aspects of bitfields are outside your control, and you should never rely on them. If you really need to control the storage layout of objects of fractional size (in bytes), you have to use shifting and masking on arrays of unsigned char.
This issue is one of the typical mistakes just about every C programmer makes at some point on their learning curve. The only way they could be avoided would be good textbooks, skilled teachers --- both of which are dangerously rare.