因为之前成功的重定向了printf函数,最近采用了C/C++混编,发现printf失效了,一直疑惑了很久,没时间去琢磨,今天突然就想起来C++中是有函数重载的概念的,所以,问题迎刃而解了,将下面的这部分随便放在一个C文件中就解决了,因为C文件时不会有函数重载的。此处采用寄存器的方式实现,方便标准库和HAL库移植。
/**
* @description: 重定向printf函数
* @return {*}
*/
#ifdef __GNUC__
__attribute__((used)) int _write(int file,char *ptr,int len)
{
while(*ptr != 0)
{
USART1->SR;
USART1->DR = (*ptr++ & (uint16_t)0x01FF);
while ((USART1->SR & (0x1UL << 6)) == 0);
}
return len;
}
#else
#pragma import(__use_no_semihosting)
//标准库需要的支持函数
struct __FILE
{
int handle;
};
FILE __stdout;
//定义_sys_exit()以避免使用半主机模式
void _sys_exit(int x)
{
x = x;
}
void _ttywrch(int ch)
{
ch = ch;
}
//以上的代码为关闭半主机模式
int fputc(int ch, FILE *f)
{
USART_SendData(USART1, (uint8_t) ch);
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
return (ch);
}
#endif