我正在 IAR 工作台上编译以下代码片段。
// global declaration
float fval = 3.14f;
uint8_t uartTxBuffer [100];
void function(void)
{
memset(uartTxBuffer,'\0',sizeof(uartTxBuffer);
sprintf(uartTxBuffer,"\n\r Value is %f",fval);
UartWrite(uart, uartTxBuffer,strlen(uartTxBuffer));
}
输出是
值为 %f//而不是 3.14
有人可以解释一下我的代码有什么问题吗?
是Uartwrite函数的问题还是我在使用C语言时犯了一些错误?
我在 Keil MDK 上使用 printf 尝试了相同的代码,它在串行终端上输出了正确的值。那么这是一个 IDE 问题吗?
有人可以指导我吗?
最佳答案
经过简短的研究后出现了这个问题
https://www.iar.com/support/tech-notes/general/problems-with-printf-floating-point-f-on-arm/
问题似乎是堆栈指针的字节对齐。 在 sprintf() 调用上设置断点并检查调试器中堆栈指针的值。
我找到的大多数答案都与FreeRTOS有关(我不知道你是否使用它):
sprintf breaking under new FreeRTOS
常见的解决方案是诉诸
a third party library called printf-stdarg.c that provides a tiny print/sprintf/printf implementation for use in cases where the libraries that come with the compiler are just too big for small embedded use
希望这会有所帮助
关于c - 串行端口 IAR 上的 Sprintf 和浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55113042/