##########################
# On command line use:
#   make all = compile project
#   make clean = clean project

##########################
# Project definitions

# project name
#PROJECT = ATX81

# target platform
TRGT = avr-

# target CPU
#MCU = atmega8
#MCU = atmega88

# CPU frequency
#F_CPU = 24000000

# list of C source files
SRC =

# list of ASM source files
ASRC = data.S main.S wait.S video.S key.S disp.S led.S eeprom.S mem.S comp.S calc.S prog.S

# optimisation level
OPT = -Os   # optimise for size
#OPT = -O3  # optimise for speed

# tools
CC = $(TRGT)gcc
LN = $(TRGT)gcc
OC = $(TRGT)objcopy
#AS = $(TRGT)gcc -x assembler-with-cpp
HEX = $(OC) -O ihex
BIN = $(OC) -O binary
#LST = $(TRGT)objdump -d -S -m avr
# -ffunction-sections ... generates a separate ELF section for each function in the source file.
#  The unused section elimination feature of the linker can then remove unused functions at link time.
# -fno-function-sections ... disable
# -fdata-sections ... generates separate ELF section for each variable
# -fno-data-sections ... disable
# -mrelax ... try to replace CALL resp. JMP instruction by the shorter RCALL resp. RJMP instruction if applicable
# -Wl ... pass following options to linker (separated with comma ,)
#     --relax ... Relax branches on certain targets
#     --gc-sections ... Remove unused sections (on some targets)
#     --no-gc-sections ... Don't remove unused sections (default)
# -ffreestanding ... Do not assume that standard C libraries and "main" exist
# -mcall-prologues
# -ftree-scev-cprop ... enable copy propagation of scalar-evolution information.
# -fno-tree-scev-cprop ... disable
# -fsplit-wide-types ... split wide types into independent registers
# -fno-split-wide-types ... disable
# -Werror ... Make all warnings into errors

# setup - eliminate unused sections
#OPT2 = -ffunction-sections -fdata-sections -Wl,--relax,--gc-sections -ffreestanding -mcall-prologues -fno-tree-scev-cprop -fno-split-wide-types -Werror

# setup - do not eliminate unused sections
OPT2 = -fno-function-sections -fno-data-sections -Wl,--relax,--no-gc-sections -ffreestanding -mcall-prologues -fno-tree-scev-cprop -fno-split-wide-types -Werror

# flags
CCFLAGS = $(OPT) -Wall -std=gnu99 -gstabs -mmcu=$(MCU) -c $(CDEF) -D$(MCU) -D F_CPU=$(F_CPU) $(OPT2)
LNFLAGS = -mmcu=$(MCU) -DF_CPU=$(F_CPU) $(OPT) $(OPT2) -D$(MCU) -Wl,--section-start=.eeprom=0x820000
OCFLAGS = -j .text -j .data
#ASFLAGS = -mmcu=$(MCU) -nostartfiles -g -D F_CPU=$(F_CPU) -Wa,-amhls=$(<:.s=.lst)


##########################
# Makefile rules

OBJS = $(ASRC:.s=.o) $(SRC:.c=.o)

all: $(OBJS) $(PROJECT).elf $(PROJECT).hex $(PROJECT).bin
# $(PROJECT).lst

%.o : %.c
	$(CC) -c $(CCFLAGS) $< -o $@

%elf: $(OBJS)
	$(LN) $(LNFLAGS) -o $@ $(OBJS)
  
%hex: %elf
	$(HEX) $< $@

%bin: %elf
	$(BIN) $< $@

#%lst: %elf
#	$(LST) $< > $@
