MODE := release
TARGET := riscv64gc-unknown-none-elf
OBJDUMP := rust-objdump --arch-name=riscv64
OBJCOPY := rust-objcopy --binary-architecture=riscv64

RUST_FLAGS := -Clink-arg=-Tsrc/linker.ld  # 使用我们自己的链接脚本
RUST_FLAGS += -Cforce-frame-pointers=yes  # 强制编译器生成帧指针
RUST_FLAGS:=$(strip ${RUST_FLAGS})

APP_DIR := src/bin
TARGET_DIR := target/$(TARGET)/$(MODE)
APPS := $(wildcard $(APP_DIR)/*.rs)
ELFS := $(patsubst $(APP_DIR)/%.rs, $(TARGET_DIR)/%, $(APPS))
BINS := $(patsubst $(APP_DIR)/%.rs, $(TARGET_DIR)/%.bin, $(APPS))


# 编译elf文件
build_elf: clean
	CARGO_BUILD_RUSTFLAGS="$(RUST_FLAGS)" \
 	cargo build --$(MODE) --target=$(TARGET)


# 把每个elf文件去掉无关代码
build: build_elf
	@$(foreach elf, $(ELFS), $(OBJCOPY) $(elf) --strip-all -O binary $(patsubst $(TARGET_DIR)/%, $(TARGET_DIR)/%.bin, $(elf));)


clean:
	rm -rf ./target*