在使用 arm-none-eabi- 工具链编译 stm32f1 程序时,可以通过以下步骤使 printf 被正确重定向:

  1. 创建一个名为 retarget.c 的源文件,用于重定向输入和输出函数。在该文件中,你可以定义 _write 函数和 _read 函数来重定向输出和输入。示例代码如下:
#include <stdio.h>
#include <sys/stat.h>

extern int __io_putchar(int ch);  // 声明外部函数 __io_putchar

int _write(int file, char *ptr, int len)
{
    int i;
    for (i = 0; i < len; i++)
    {
        __io_putchar(*ptr++);
    }
    return len;
}

int _read(int file, char *ptr, int len)
{
    // 实现自定义的输入函数(可选)
    return len;
}

// 将 _write 函数重定向到 __io_putchar 函数,以实现 printf 的重定向
void _ttywrch(int ch)
{
    __io_putchar(ch);
}

// 定义 _sbrk 函数,以满足动态内存分配的要求(可选)
caddr_t _sbrk(int incr)
{
    extern char _end;  // 由链接脚本定义的堆起始地址
    static char *heap_end;
    char *prev_heap_end;

    if (heap_end == 0)
    {
        heap_end = &_end;
    }
    prev_heap_end = heap_end;

    if (heap_end + incr > stack_ptr)
    {
        _write(1, "Heap and stack collision\n", 25);
        abort();
    }

    heap_end += incr;
    return (caddr_t)prev_heap_end;
}

// 定义 _exit 函数,以满足程序退出的要求(可选)
void _exit(int status)
{
    _write(1, "exit\n", 5);
    while (1)
    {
        ;
    }
}
  1. 在链接脚本(.ld 文件)中添加对 retarget.c 文件的引用,以确保该文件被编译和链接至最终的可执行文件中。

  2. 在 Makefile 或编译命令中添加 -specs=nosys.specs 选项,用于禁用 nano.specs,以避免与自定义的重定向函数产生冲突。

通过以上步骤,你应该能够成功地重定向 printf 函数。请注意,以上代码仅提供了一个基本的示例,你可以根据自己的需求进行修改和扩展

使用 arm-none-eabi- 工具链编译 stm32f1 程序时使用了 -specs=nanospecs 选项导致使用 _io_putchar 重定向 printf 无法成功。请问如何使 printf 被正确重定向?

原文地址: http://www.cveoy.top/t/topic/hV1G 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录