# This makefile expects the following variables to be externally
# defined:
# XTRGT    - The compiler prefix, as example arm-elf-
# XMCFLAGS - MCU/CPU related options
# XOPT     - Compiler extra options
# XSRC     - Extra sources to be included
# XASM     - Extra asm sources to be included
# XINCDIR  - Extra include directories
# XDEFS    - Extra definitions

CC   = $(XTRGT)gcc
AS   = $(XTRGT)gcc -x assembler-with-cpp
OD   = $(XTRGT)objdump
BIN  = $(XTRGT)objcopy -O binary

# Constants
PROJECT = ch
LDSCRIPT= ch.ld

# Imported source files
CHIBIOS = ../..
include ${CHIBIOS}/os/kernel/kernel.mk

# List ARM-mode C source files here
SRC =  ${KERNSRC} \
       ${XSRC}

# List ASM source files here
ASMSRC = ${XASM}

# List all user directories here
UINCDIR = $(KERNINC)

# Default options here
OPT =

# Warning options here
WARN = -Wall -Wstrict-prototypes

INCDIR  = $(patsubst %,-I%,$(UINCDIR) $(XINCDIR))
DEFS    = -D__NEWLIB__ $(XDEFS)
COBJS   = $(SRC:.c=.o)
ASMOBJS = $(ASMSRC:.s=.o)
OBJS	= $(ASMOBJS) $(COBJS)
MCFLAGS = $(XMCFLAGS)

ODFLAGS	= -x --syms
ASFLAGS = $(MCFLAGS) -Wa,-amhls=$(<:.s=.lst) $(DEFS)
CPFLAGS = $(MCFLAGS) $(OPT) $(XOPT) $(WARN) -Wa,-alms=$(<:.c=.lst) $(DEFS)
LDFLAGS = $(MCFLAGS) -nostartfiles -T$(LDSCRIPT) -Wl,-Map=$(PROJECT).map,--cref,--no-warn-mismatch

# Generate dependency information
#CPFLAGS += -MD -MP -MF .dep/$(@F).d

#
# Makefile rules
#
all: $(OBJS) $(PROJECT).elf $(PROJECT).bin $(PROJECT).dmp

$(COBJS) : %.o : %.c
	@echo
	$(CC) -c $(CPFLAGS) -I . $(INCDIR) $< -o $@

$(ASMOBJS) : %.o : %.s
	@echo
	$(AS) -c $(ASFLAGS) -I . $(INCDIR) $< -o $@

%elf: $(OBJS)
	@echo
	$(CC) $(ASMOBJS) $(COBJS) $(LDFLAGS) $(LIBS) -o $@

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

%dmp: %elf
	$(OD) $(ODFLAGS) $< > $@

clean:
	-rm -f $(OBJS)
	-rm -f $(PROJECT).elf
	-rm -f $(PROJECT).dmp
	-rm -f $(PROJECT).map
	-rm -f $(PROJECT).bin
	-rm -f $(SRC:.c=.c.bak)
	-rm -f $(SRC:.c=.lst)
	-rm -f $(ASMSRC:.s=.s.bak)
	-rm -f $(ASMSRC:.s=.lst)
	-rm -fR .dep

#
# Include the dependency files, should be the last of the makefile
#
#-include $(shell mkdir .dep 2>/dev/null) $(wildcard .dep/*)
