# Makefile - STM32F405 (olimex-stm32-h405) 串口打印 QEMU 仿真
# 工具链若未加入 PATH，请改为完整路径：
#   CC   := D:/ProgramData/arm_tools/xpack-arm-none-eabi-gcc-15.2.1-1.1/bin/arm-none-eabi-gcc
#   QEMU := D:/ProgramData/arm_tools/qemu/qemu-system-arm

CC      = arm-none-eabi-gcc
QEMU    = qemu-system-arm

BUILD   := build
MCU     := olimex-stm32-h405
LDSCRIPT:= core/linker.ld

CPU     := -mcpu=cortex-m4 -mthumb
INCLUDES:= -Ihal -Idrivers/inc -Ibsp/olimex_stm32_h405
CFLAGS  := $(CPU) -nostdlib -nostartfiles -ffreestanding -Wall -Wextra $(INCLUDES)

ELF := $(BUILD)/firmware.elf
BIN := $(BUILD)/firmware.bin

.PHONY: all bin run clean

all: $(ELF)

$(ELF): $(BUILD)/startup.o $(BUILD)/system.o $(BUILD)/uart.o $(BUILD)/gpio.o $(BUILD)/board.o $(BUILD)/main.o $(LDSCRIPT)
	$(CC) $(CPU) -T $(LDSCRIPT) -nostdlib -Wl,-Map=$(BUILD)/firmware.map -o $@ $(filter-out $(LDSCRIPT),$^)

$(BUILD)/startup.o: core/startup_stm32f405.s
	@if not exist $(BUILD) mkdir $(BUILD)
	$(CC) $(CPU) -c $< -o $@

$(BUILD)/system.o: core/system_stm32f405.c
	@if not exist $(BUILD) mkdir $(BUILD)
	$(CC) $(CFLAGS) -c $< -o $@

$(BUILD)/uart.o: drivers/src/uart.c
	@if not exist $(BUILD) mkdir $(BUILD)
	$(CC) $(CFLAGS) -c $< -o $@

$(BUILD)/gpio.o: drivers/src/gpio.c
	@if not exist $(BUILD) mkdir $(BUILD)
	$(CC) $(CFLAGS) -c $< -o $@

$(BUILD)/board.o: bsp/olimex_stm32_h405/board.c
	@if not exist $(BUILD) mkdir $(BUILD)
	$(CC) $(CFLAGS) -c $< -o $@

$(BUILD)/main.o: app/main.c
	@if not exist $(BUILD) mkdir $(BUILD)
	$(CC) $(CFLAGS) -c $< -o $@

bin: $(BIN)
$(BIN): $(ELF)
	arm-none-eabi-objcopy -O binary $< $@

run: $(ELF)
	$(QEMU) -M $(MCU) -kernel $(ELF) -serial stdio -display none

clean:
	if exist $(BUILD) rmdir /s /q $(BUILD)
