BINARY = rtdriver
OBJS = obj/rtdriver.o

PREFIX          ?= arm-none-eabi
CC              = $(PREFIX)-gcc
LD              = $(PREFIX)-gcc
OBJCOPY         = $(PREFIX)-objcopy
OBJDUMP         = $(PREFIX)-objdump
GDB             = $(PREFIX)-gdb

TOOLCHAIN_DIR   = `dirname \`which $(CC)\``/../$(PREFIX)

ARCH_FLAGS      = -mthumb -mcpu=cortex-m3 -msoft-float
CFLAGS          += -Os -g -Wall -Wextra -I inc -I$(TOOLCHAIN_DIR)/include \
                   -fno-common $(ARCH_FLAGS) -MD -DSTM32F1
LDSCRIPT        = linker.ld
LDFLAGS         += -Wl,--start-group -lc -lgcc -lnosys -Wl,--end-group \
                   -L$(TOOLCHAIN_DIR)/lib/stm32/f1/ \
                   -T$(LDSCRIPT) -nostartfiles -Wl,--gc-sections \
                   $(ARCH_FLAGS) -mfix-cortex-m3-ldrd

ifneq ($(V),1)
Q := @
NULL := 2>/dev/null                   
else
LDFLAGS += -Wl,--print-gc-sections
endif

.SUFFIXES: .elf .bin .hex .srec .list .images
.SECONDEXPANSION:
.SECONDARY:

all: images

gdb: images
        $(GDB) bin/$(BINARY).elf

upload: images
        stm32flash -k -w bin/$(BINARY).bin /dev/ttyUSB0

images: $(OBJS) bin/$(BINARY).elf bin/$(BINARY).bin bin/$(BINARY).hex bin/$(BINARY).srec bin/$(BINARY).list

bin/%.bin: bin/%.elf
        @echo "  OBJCOPY $@"
        $(Q)$(OBJCOPY) -Obinary $< $@

bin/%.hex: bin/%.elf
        @echo "  OBJCOPY $@"
        $(Q)$(OBJCOPY) -Oihex $< $@

bin/%.srec: bin/%.elf
        @echo "  OBJCOPY $@"
        $(Q)$(OBJCOPY) -Osrec $< $@

bin/%.list: bin/%.elf
        @echo "  OBJDUMP $@"
        $(Q)$(OBJDUMP) -S $< > $@

bin/%.elf: $(OBJS) $(LDSCRIPT)
        @echo "  LD      $@"
        $(Q)$(LD) -o $@ $(OBJS) -lopencm3_stm32f1 $(LDFLAGS)


obj/%.o: src/%.c Makefile
        @echo "  CC      $@"
        $(Q)$(CC) $(CFLAGS) -o $@ -c $<


obj/%.o: src/%.s Makefile
        @echo "  ASM     $@"
        $(Q)$(CC) $(CFLAGS) -o $@ -c $<

clean:
        $(Q)rm -f obj/*
        $(Q)rm -f bin/*

.PHONY: all clean images upload gdb