.DEFAULT_GOAL := all

include Makeconf

# Auto tracking of headers
CXXFLAGS += -MMD

all-modules := $(foreach t,$(TARGETS),$(modules_$(t)))

depfiles := $(patsubst %.o,%.d,$(filter %.o,$(all-modules)))

-include $(depfiles)

clean-objs := $(TARGETS) $(all-modules) $(depfiles)
cmd = $(VERBOSE)g++ $(CXXFLAGS) $(LDFLAGS_$@) -o $@ $^
msg = $(or $(verb_$@),finalize) $@

ifneq ($V,1)
VERBOSE := @
endif

.PHONY: all test clean

all: $(or $(DEFAULT_TARGETS),$(TARGETS))

-include $(depfiles)

clean:
	rm -rf $(clean-objs)

test: vgbc.test
	@echo " ... run test $<"
	$(VERBOSE)./$< $(if $(V),-s)

%.o: %.cpp
	@echo " ... build $@"
	$(VERBOSE)g++ $(CXXFLAGS) -c -o $@ $<

define target_rule
$(1): $$(modules_$(1))
	@echo " ..." $$(or $$(msg_$(1)),$$(msg))
	$$(VERBOSE)$$(or $$(cmd_$(1)),$$(cmd))
endef

$(foreach t,$(TARGETS),$(eval $(call target_rule,$(t))))