Keil MDK 的 STM32 开发问题:重定向 printf 函数效果不生效(Keil MDK 中标准库未正确链接)

发布于:2025-06-30 ⋅ 阅读:(20) ⋅ 点赞:(0)
#include "stm32f10x.h"
#include <stdio.h>

void delay_us(uint16_t us);
void delay_ms(uint16_t ms);
void delay_s(uint16_t s);
void USART1_SendChar(char c);

int fputc(int c, FILE *file)
{
    USART1_SendChar(c);
    return c;
}

int main()
{
    // 串口 USART1 TX 对应 PA9

    // APB2 使能时钟
    RCC->APB2ENR |= RCC_APB2ENR_IOPAEN;
    RCC->APB2ENR |= RCC_APB2ENR_USART1EN;

    // 配置 PA9 为复用推挽输出,最大速度 50MHz
    GPIOA->CRH &= ~(GPIO_CRH_CNF9 | GPIO_CRH_MODE9);
    GPIOA->CRH |= GPIO_CRH_CNF9_1;
    GPIOA->CRH |= GPIO_CRH_MODE9_1 | GPIO_CRH_MODE9_0;

    // 配置 USART1 波特率为 115200
    USART1->BRR = 0x271;

    // 使能 USART1
    USART1->CR1 |= USART_CR1_UE | USART_CR1_TE;

    while (1)
    {
        printf("Hello World 1\r\n");
        delay_ms(500);
        printf("Hello World 2\r\n");
        delay_ms(500);
    }
}
void delay_us(uint16_t us)
{
    SysTick->LOAD = 72 * us;
    SysTick->CTRL = 0x05;
    while (!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk))
        ;
    SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}

void delay_ms(uint16_t ms)
{
    while (ms--)
    {
        delay_us(1000);
    }
}

void delay_s(uint16_t s)
{
    while (s--)
    {
        delay_ms(1000);
    }
}

void USART1_SendChar(char c)
{
    while (!(USART1->SR & USART_SR_TXE))
        ;
    USART1->DR = c;
}
  • 在 STM32 开发中,执行上述重定向 printf 函数的程序,重定向 printf 函数效果不生效
问题原因
  • 这个问题主要的原因可能是在 Keil MDK 中标准库未正确链接
处理策略
  • 在 Keil 中正确链接标准库
  1. 点击 【Options for Target】
  1. 点击 【Target】 -> 勾选 【Use MicroLIB】
  1. 重新编译程序 -> 烧录程序