## Example makefile for arm-none-eabi-gcc and LPC-microcontrollers

OUTPUT_NAME = main

## Used tools
# C compiler frontend
CC = arm-none-eabi-gcc
OBJDUMP = arm-none-eabi-objdump

## list files to compile here (suffix: *.o)
OBJS = ./src/crt0.o ./src/STM32F100.o ./src/EEPROM.o ./src/LCD.o ./src/main.o

## Path and name of the linker script
LINKER_SCRIPT = STM32F100.ld

## Flags
# processor-dependent flags
MCU_FLAGS = -mthumb -mcpu=cortex-m3 -mfloat-abi=soft
# Compiler flags
CFLAGS = $(MCU_FLAGS) 
CFLAGS += -Wall -O3 -g3 -fno-common -fmessage-length=0 -fno-builtin -MMD -MP -std=c99
CFLAGS += -ffunction-sections -fdata-sections
# Linker flags
LDFLAGS = $(MCU_FLAGS) $(CFLAGS)
LDFLAGS += -T$(LINKER_SCRIPT)
LDFLAGS += -nostartfiles -Wl,--gc-sections,-print-memory-usage
LDFLAGS += # more options, e.g. libraries

## Rules
all: $(OUTPUT_NAME).elf $(OUTPUT_NAME).lss create_bin
.PHONY: clean

# Rule for creating the .elf file
$(OUTPUT_NAME).elf: $(OBJS) makefile
	@echo Linking final file...
	@$(CC) $(CFLAGS) -o $(OUTPUT_NAME).elf $(OBJS) $(LDFLAGS)

# Rule for compiling every needed c file 
%.o: %.c makefile
	@echo Compiling file $<...
	@$(CC) -c $(CFLAGS) -o $@ $<

# Rule for generating a disassembly
%.lss: %.elf
	@echo Generating disassembly...
	@$(OBJDUMP) -d -S $< > $@

# Create final binary
create_bin:
	arm-none-eabi-objcopy -v -O binary $(OUTPUT_NAME).elf
	mv $(OUTPUT_NAME).elf firmware.bin

# delete all created files
clean:
	@echo Cleaning up...
	@$(RM) $(OBJS) $(OUTPUT_NAME).elf $(OUTPUT_NAME).lss $(OBJS:.o=.d) $(OBJS:.o=.i) $(OBJS:.o=.su)

flash:
	stm32flash -w firmware.bin -v /dev/ttyACM0

flash_external:
	stm32flash -w firmware.bin -v /dev/ttyUSB0

# Note: dtr and rts work inverted somehow...
flash_external_rts_dtr:
	stm32flash -w firmware.bin -v -R -i -dtr,rts,-rts:dtr,rts,-rts /dev/ttyUSB0

everything:
	clear && make && make clean && make flash_external_rts_dtr

# include C dependencies
-include $(OBJS:.o=.d)
