PREFIX ?= arm-none-eabi-
CC := $(PREFIX)gcc
LD := $(PREFIX)gcc

OPT ?= -O0
DEBUG ?= -ggdb3

CFLAGS = -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16
CFLAGS += -specs=nano.specs -ffunction-sections

CFLAGS += -std=c89 -Werror -Wall -Wextra
CFLAGS += $(OPT) $(DEBUG)
CFLAGS += -Wno-unused-variable -Wshadow -Wimplicit-function-declaration
CFLAGS += -Wredundant-decls -Wstrict-prototypes -Wundef
CFLAGS += -Wno-unused-function -Wno-unused-parameter
CFLAGS += -Wno-unused-but-set-variable
CFLAGS += -fdiagnostics-color=never -fno-diagnostics-show-caret

LDFLAGS = -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16
LDFLAGS += -static -nostartfiles
LDFLAGS += -Tlink.ld
LDFLAGS += $(OPT) $(DEBUG)
LDFLAGS += -Wl,--start-group -lc -lgcc -lnosys -Wl,--end-group
LDFLAGS += -Wl,--gc-sections
LDFLAGS += -Wl,--fatal-warnings

block.o: private TARGET_FLAGS \
		= -DOPT_BMALLOC_BLEN=128 -DOPT_BMALLOC_MLEN_BLOCK=32

test_bmalloc.elf: test.o bmalloc.o

%.o: private TARGET_FLAGS =
%.o: %.c
	$(CC) $(CFLAGS) $(TARGET_FLAGS) -MMD -o $@ -c $<

%.o: %.s
	$(CC) $(CFLAGS) $(TARGET_FLAGS) -MMD -o $@ -c $<

%.elf: %.o vector.o assert.o
	$(LD) $(LDFLAGS) $^ -o $@

qemu: test_bmalloc.elf
	qemu-system-arm -M netduinoplus2 -s -nographic -semihosting \
		-kernel $<

clean:
	rm -f ./*.o ./*.elf ./*.d
.PHONY: clean

ifneq (clean, $(MAKECMDGOALS))
-include $(shell find . -type f -name '*.d' 2> /dev/null)
endif

