Close

Extending makefile for tracing, debug and log levels

A project log for Sparkfun RED-V bare metal

I wanted to learn RISC-V, not on an emulator, but on a real bare metal RISC-V processor. Even though Sparkfun RED-V is no longer produced.

olaf-baeyensOlaf Baeyens 10/27/2024 at 17:130 Comments

Improving the make files, we now want to to compile with debug, trace and logging level.

make DEBUG_LEVEL=2 TRACE_LEVEL=1 LOG_LEVEL=5

Complete makefile

# Toolchain
TOOLCHAIN_PREFIX = riscv64-unknown-elf-
CC       = $(TOOLCHAIN_PREFIX)gcc
OBJCOPY  = $(TOOLCHAIN_PREFIX)objcopy

# Default flag values (can be overridden from the command line)
DEBUG_LEVEL ?= 2
TRACE_LEVEL ?= 1
LOG_LEVEL   ?= 5

# Flags
ASFLAGS = -march=rv32g -mabi=ilp32 -static -mcmodel=medany \
          -fvisibility=hidden -nostdlib -nostartfiles -I$(INCLUDE_DIR)
LDFLAGS = -T sparkfun-red-v.ld

# Add flag definitions to ASFLAGS
ASFLAGS += -DDEBUG_LEVEL=$(DEBUG_LEVEL) -DTRACE_LEVEL=$(TRACE_LEVEL) -DLOG_LEVEL=$(LOG_LEVEL)

# Directories
SRC_DIR          = src
BOOT_DIR         = $(SRC_DIR)/boot
INCLUDE_DIR      = $(SRC_DIR)/include
DATA_DIR         = $(SRC_DIR)/data
UNIT_TESTS_DIR   = $(SRC_DIR)/unit-tests
MODULES_DIR      = $(SRC_DIR)/modules
BUILD_DIR        = build

# Source Files
GLOBAL_CONSTANTS_FILE = $(INCLUDE_DIR)/global_constants.s

SRC = $(GLOBAL_CONSTANTS_FILE) \
      $(INCLUDE_DIR)/constants.s \
      $(DATA_DIR)/data.s \
      $(DATA_DIR)/rodata.s \
      $(DATA_DIR)/bss.s \
      $(wildcard $(UNIT_TESTS_DIR)/strings-module/*.s) \
      $(wildcard $(MODULES_DIR)/debug-module/*.s) \
      $(wildcard $(MODULES_DIR)/strings-module/*.s) \
      $(wildcard $(MODULES_DIR)/info-module/*.s) \
      $(BOOT_DIR)/boot.s \
      $(SRC_DIR)/main.s 

# Object Files
OBJ = $(patsubst $(SRC_DIR)/%.s,$(BUILD_DIR)/%.o,$(SRC))

# Targets
ELF = $(BUILD_DIR)/main.elf
HEX = $(BUILD_DIR)/main.hex

.PHONY: all clean

# Default Target
all: $(BUILD_DIR) $(HEX)

# Create build directory
$(BUILD_DIR):
	@mkdir -p $(BUILD_DIR)

# Rule to build hex file from ELF
$(HEX): $(ELF)
	$(OBJCOPY) -O ihex $< $@

# Rule to build ELF from object files
$(ELF): $(OBJ)
	$(CC) $(ASFLAGS) $(LDFLAGS) $^ -o $@

# Rule to compile .s files to .o files
$(BUILD_DIR)/%.o: $(SRC_DIR)/%.s
	@mkdir -p $(dir $@)
	$(CC) $(ASFLAGS) -c $< -o $@

# Clean up build artifacts
clean:
	rm -rf $(BUILD_DIR)

Discussions