Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c - Struct packing and alignment with mingw

I am emulating code from an embedded system (stm32, Keil μVision 5, MDK-ARM) on a PC (mingw32, 32bit arch). The alignment of the ARM compiler does not match my desktop mingw build:

// ARM Code (ARM compiler uses __packed)
typedef __packed struct _file
{
    uint8_t var1;
    uint16_t var2;
} FILE;

// PC mingw gcc code trying to emulate layout above.
typedef struct __attribute__((packed, aligned(1))) _file
{
    uint8_t var1;
    uint16_t var2;
} FILE;


In the source I do the following: file.var1 = 0x22; file.var2 = 0xAA55; which is then written to memory. When I read the memory on the embedded system it shows 0x22, 0x55, 0xAA. On the Windows machine it reads 0x22, 0xFF, 0x55, 0xAA, with padding at the 2nd byte. How can I correct this behaviour?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I fixed it by myself -> Compiling with -mno-ms-bitfields helps! The code above is indeed correct. It is necessary to tell mingw to use gcc's bitfield organisation instead of the microsoft style. Though the code can be uncompileable with microsoft compilers then, I do not care at this point.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...