问题描述
使用STM32F407开发,开启了FPU,因为要使用Modbus协议,所以结构体使用1字节对齐的方式
#pragma pack(1)
typedef struct {
uint8_t uData;
float fValue;
}TestCtx;
#pragma pack()
出现错误的情况:
//定义的全局变量
TestCtx tTest = {1, 100.3};
TestCtx tTest1 = {1, 100.3};
TestCtx tTest2 = {1, 20.3};
float *pfValue = &(tTest2.fValue);
//main 函数中
int main ()
{
*pfValue = tTest.fValue * tTest1.fValue;
}
正常情况:
//定义的全局变量
TestCtx tTest = {1, 100.3};
TestCtx tTest1 = {1, 100.3};
TestCtx tTest2 = {1, 20.3};
float *pfValue = &(tTest2.fValue);
//main 函数中
int main ()
{
tTest2.fValue = tTest.fValue * tTest1.fValue;
}
上面的例子是写的一个测试用例,平常使用过程中,是将tTest2.fValue取地址之后,带入其他函数中,将计算结果赋值。会出现HardFault_Handler异常。
问题原因
使用FPU进行计算的时候,单精度的需要4字节对齐,双精度的需要8字节对齐,所以执行*pfValue = tTest.fValue * tTest1.fValue;的时候,在上图的位置出现Fault_Handler异常。
解决办法
该方法不算完美,但至少解决了一定问题:
在调用传入指针(1字节对齐的float类型数据的指针)的函数前,创建一个临时float变量,将该临时变量作为实参传入,调用函数,然后将临时变量赋值给1字节对齐的float类型变量。
疑问
同样是地址不能被4整除的tTest2.fValue = tTest.fValue * tTest1.fValue; 却能够执行成功,这个问题还没想明白原因。