##############################################################################
BUILD = build
BIN = Demo

##############################################################################
.PHONY: all directory clean size

CC = arm-none-eabi-g++
OBJCOPY = arm-none-eabi-objcopy
SIZE = arm-none-eabi-size

ifeq ($(OS), Windows_NT)
  MKDIR = gmkdir
else
  MKDIR = mkdir
endif

CXXFLAGS += -W -Wall --std=c++17 -fno-rtti -fno-exceptions -flto -Os
CXXFLAGS += -fno-diagnostics-show-caret
CXXFLAGS += -fdata-sections -ffunction-sections
CXXFLAGS += -funsigned-char -funsigned-bitfields
CXXFLAGS += -mcpu=cortex-m23 -mthumb --specs=nano.specs --specs=nosys.specs
CXXFLAGS += -MD -MP -MT $(BUILD)/$(*F).o -MF $(BUILD)/$(@F).d

LDFLAGS += -mcpu=cortex-m23 -mthumb --specs=nano.specs --specs=nosys.specs -flto
LDFLAGS += -Wl,--gc-sections
LDFLAGS += -Wl,--script=../linker/saml10e16a.ld

INCLUDES += \
  -I../include \
  -I/home/duraid/arm/fmt.git/include \
  -I/home/duraid/folly.git \
  -I../tc \
  -I..

SRCS += \
  ../main.c \
  ../sbrk.c \
  ../SmallVector.c \
  ../startup_saml10.c

DEFINES += \
  -D__SAML10E16A__ \
  -DDONT_USE_CMSIS_INIT \
  -DF_CPU=16000000

CXXFLAGS += $(INCLUDES) $(DEFINES)

OBJS = $(addprefix $(BUILD)/, $(notdir %/$(subst .c,.o, $(SRCS))))

all: directory $(BUILD)/$(BIN).elf $(BUILD)/$(BIN).hex size

$(BUILD)/$(BIN).elf: $(OBJS)
	@echo LD $@
	@$(CC) $(LDFLAGS) $(OBJS) $(LIBS) -o $@

$(BUILD)/$(BIN).hex: $(BUILD)/$(BIN).elf
	@echo OBJCOPY $@
	@$(OBJCOPY) -O ihex $^ $@

$(BUILD)/$(BIN).bin: $(BUILD)/$(BIN).elf
	@echo OBJCOPY $@
	@$(OBJCOPY) -O binary $^ $@

%.o:
	@echo CC $@
	@$(CC) $(CXXFLAGS) $(filter %/$(subst .o,.c,$(notdir $@)), $(SRCS)) -c -o $@

directory:
	@$(MKDIR) -p $(BUILD)

size: $(BUILD)/$(BIN).elf
	@echo size:
	@$(SIZE) -t $^

clean:
	@echo clean
	@-rm -rf $(BUILD)

-include $(wildcard $(BUILD)/*.d)

