使用 mingw 进行结构打包和对齐 [英] Struct packing and alignment with mingw

查看:20
本文介绍了使用 mingw 进行结构打包和对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 PC(mingw32,32 位架构)上模拟来自嵌入式系统(stm32、Keil µVision 5、MDK-ARM)的代码.ARM 编译器的对齐方式与我的桌面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;


在源代码中,我执行以下操作: file.var1 = 0x22;file.var2 = 0xAA55; 然后写入内存.当我在嵌入式系统上读取内存时,它显示 0x22, 0x55, 0xAA.在 Windows 机器上,它读取 0x22, 0xFF, 0x55, 0xAA,在第 2nd 字节填充.我该如何纠正这种行为?


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?

推荐答案

我自己修复了 -> 使用 -mno-ms-bitfields 进行编译有帮助!上面的代码确实是正确的.有必要告诉mingw使用gcc的位域组织而不是microsoft的风格.虽然那时代码可能无法用微软编译器编译,但我现在不在乎.

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.

这篇关于使用 mingw 进行结构打包和对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆