此方案可以一并解决printf与scanf函数的重定向
可参考博客
GCC Arm 11.3rel1, 12.2编译提示 _close is not implemented and will always fail - Milton - 博客园
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include "usart.h"
__attribute__((weak)) int _close(int fd)
{
if (fd >= STDIN_FILENO && fd <= STDERR_FILENO)
return 0;
errno = EBADF;
return -1;
}
__attribute__((weak)) int _lseek(int fd, int ptr, int dir)
{
(void)fd;
(void)ptr;
(void)dir;
errno = EBADF;
return -1;
}
__attribute__((weak)) int _isatty_r(int fd)
{
if (fd >= STDIN_FILENO && fd <= STDERR_FILENO)
return 1;
errno = EBADF;
return 0;
}
__attribute__((weak)) int _fstat_r(int fd, struct stat *st)
{
if (fd >= STDIN_FILENO && fd <= STDERR_FILENO)
{
st->st_mode = S_IFCHR;
return 0;
}
errno = EBADF;
return 0;
}
int __io_getchar(void)
{
uint8_t ch = 0;
// Clear the Overrun flag just before receiving the first character
__HAL_UART_CLEAR_OREFLAG(&huart1);
HAL_UART_Receive(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
__attribute__((weak)) int _read(int file, char *ptr, int len)
{
(void)file;
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
*ptr++ = __io_getchar();
}
return len;
}
int _write(int file, char *ptr, int len)
{
HAL_UART_Transmit(&huart1, (uint8_t *)ptr, len, HAL_MAX_DELAY);
return len;
}