########################################
## bare bones makefile for ARM Cortex ##
########################################

NAME      = PruefadapterMaster

MKDIR     = mkdir -p

SRCS      = $(wildcard src/*.c)
SRCS     += $(wildcard cmsis/MKL05Z4/*.c)
SRCS     += $(wildcard cmsis/MKL05Z4/*.s)

INCDIRS   = src/
INCDIRS  += cmsis/
INCDIRS  += cmsis/MKL05Z4/

DEFINES   = 

LSCRIPT   = cmsis/MKL05Z4/MKL05Z4.ld

BUILDDIR  = build/

CFLAGS    = -ffunction-sections
CFLAGS   += -mlittle-endian
CFLAGS   += -mthumb
CFLAGS   += -mcpu=cortex-m0plus
CFLAGS   += -std=c11
CFLAGS   += -ggdb
CFLAGS   += -Os -flto
#CFLAGS   += Og

LFLAGS    = --specs=nano.specs
LFLAGS   += --specs=nosys.specs
LFLAGS   += -nostartfiles
LFLAGS   += -Wl,--gc-sections
LFLAGS   += -T$(LSCRIPT)
LFLAGS   += -lm

WFLAGS    = -Wall
WFLAGS   += -Wextra 
WFLAGS   += -Werror  
WFLAGS   += -Wno-error=unused-function 
WFLAGS   += -Wno-error=unused-variable 
WFLAGS   += -Wno-error=unused-but-set-variable 
WFLAGS   += -Wfatal-errors 
WFLAGS   += -Warray-bounds 
WFLAGS   += -Wno-unused-parameter

GCCPREFIX = arm-none-eabi-
CC        = $(GCCPREFIX)gcc
OBJCOPY   = $(GCCPREFIX)objcopy
OBJDUMP   = $(GCCPREFIX)objdump
SIZE	  = $(GCCPREFIX)size

INCLUDE   = $(addprefix -I,$(INCDIRS))
OBJS      = $(addprefix $(BUILDDIR),$(addsuffix .o,$(basename $(SRCS))))


###########
## rules ##
###########

.PHONY: all
all: $(OBJS)
all: $(BUILDDIR)$(NAME).elf
all: $(BUILDDIR)$(NAME).bin
all: $(BUILDDIR)$(NAME).lst
all: print_size

.PHONY: clean
clean: 
	$(RM) -rf $(wildcard $(BUILDDIR)*)

# compiler
$(BUILDDIR)%.o: %.c
	$(MKDIR) $(dir $@)
	$(CC) -MMD -c -o $@ $(INCLUDE) $(DEFINES) $(CFLAGS) $(WFLAGS) $<

# assembler
$(BUILDDIR)%.o: %.s
	$(MKDIR) $(dir $@)
	$(CC) -c -x assembler-with-cpp -o $@ $(INCLUDE) $(DEFINES) $(CFLAGS) $(WFLAGS) $<

# linker
$(BUILDDIR)%.elf: $(OBJS)
	$(CC) -o $@ $(CFLAGS) $(LFLAGS) $^

%.bin: %.elf
	$(OBJCOPY) -O binary -S $< $@ 

%.s19: %.elf
	$(OBJCOPY) -O srec -S $< $@

%.lst: %.elf
	$(OBJDUMP) -D $< > $@ 

.PHONY: print_size
print_size: $(BUILDDIR)$(NAME).elf
	$(SIZE) $(BUILDDIR)$(NAME).elf
	

#####################
## Advanced Voodoo ##
#####################

# try to include any compiler generated dependency makefile snippet *.d
# that might exist in BUILDDIR (but don't complain if it doesn't yet).
DEPS = $(addprefix $(BUILDDIR),$(patsubst %.c,%.d,$(filter %.c,$(SRCS))))
-include $(DEPS)

# make the object files also depend on the makefile itself
$(OBJS): Makefile
