################################Shimatta Makefile####################################
#CPU:		STM32F746ZGT
#Compiler:	arm-none-eabi
#####################################################################################
#Add Files and Folders below#########################################################
CFILES 	= main.c syscalls/syscalls.c setup/system_init.c startup/startup_stm32f746.c
ASFILES =
INCLUDEPATH = -Iinclude

OBJDIR := obj

TARGET	= project
LIBRARYPATH = -Lstartup -Ldsp
LIBRARIES = -larm_cortexM7lfsp_math

DEFINES = -DSTM32F746xx -DSTM32F7XX -DARM_MATH_CM7
mapfile = memmap

##Custom Files###

#TODO


###################################################################################
CC=arm-none-eabi-gcc
OBJCOPY=arm-none-eabi-objcopy
OBJDUMP=arm-none-eabi-objdump
SIZE=arm-none-eabi-size

LFLAGS = -mlittle-endian -mthumb -mcpu=cortex-m7 -mthumb-interwork 
LFLAGS += -mfloat-abi=hard -mfpu=fpv5-sp-d16 --disable-newlib-supplied-syscalls -nostartfiles
LFLAGS += -Tstm32f746zgt-axim.ld -Wl,-Map=$(mapfile).map -Wl,--gc-sections
LFLAGS += -Wl,--print-memory-usage

CFLAGS = -fmessage-length=0 -mlittle-endian -mthumb -mcpu=cortex-m7 -mthumb-interwork
CFLAGS += -mfloat-abi=hard -mfpu=fpv5-sp-d16 -nostartfiles -Wall

####################################################################################

OBJ = $(CFILES:%.c=$(OBJDIR)/%.c.o)
ASOBJ = $(ASFILES:%.S=$(OBJDIR)/%.S.o)

DEPENDENCY_FILES = $(CFILES:%.c=$(OBJDIR)/%.c.d) $(ASFILES:%.S=$(OBJDIR)/%.S.d)

default: $(TARGET).elf

%.bin: %.elf
	$(OBJCOPY) -O binary $^ $@
%.hex: %.elf
	$(OBJCOPY) -O ihex $^ $@


#Linking
$(TARGET).elf: $(OBJ) $(ASOBJ)
	@$(CC) $(LFLAGS) $(LIBRARYPATH) -o $@ $^ $(LIBRARIES)
	@$(SIZE) $@	

#Compiling
$(OBJ):
	@echo [CC] $@
	@mkdir -p $(@D)
	@$(CC) $(CFLAGS) -MMD -MT $@ $(INCLUDEPATH) $(DEFINES) -o $@ -c $(@:$(OBJDIR)/%.c.o=%.c)
	
$(ASOBJ):
	@echo [AS] $@
	@mkdir -p $(@D)
	@$(CC) $(CFLAGS) -MMD -MT $@ $(INCLUDEPATH) $(DEFINES) -o $@ -c $(@:$(OBJDIR)/%.S.o=%.S)

.PHONY: clean mrproper objcopy disassemble

disassemble: $(TARGET).elf
	$(OBJDUMP) -D -s $< > $(TARGET).lss

objcopy: $(TARGET).bin $(TARGET).hex

mrproper:
	rm -f $(TARGET).pro

clean:
	@echo [RM] in $(OBJDIR)
	@rm -f $(TARGET).elf $(TARGET).bin $(TARGET).hex $(OBJ) $(ASOBJ) $(mapfile).map $(TARGET).lss $(DEPENDENCY_FILES)
	@rm -rf $(OBJDIR)/*

# Include dependency files, if available
-include $(DEPENDENCY_FILES)
