# Define the compiler to be used

CC     := g++

# This is the program name

PROG    = example

# Define an (arbitrary) library to be used (in addition to standard libraries)

LIBRARY = Mylib

# These are the sources that will end up in the library. In this case we
# choose all files ending in .cc with the exception of the main program

SOURCES = $(filter-out $(PROG).cc,$(wildcard *.cc))

# This specifies the corresponding object files. Look at the documentation
# of the 'patsubst' function to see how this works.

OBJECTS = $(SOURCES:.cc=.o)

# We also need a list of header files (see later). Here, we'll again choose
# to consider all files ending in .hh as relevant header files.

HEADERS = $(wildcard *.hh)

# This specifies the flags to be passed to the linker

LDFLAGS = -L`pwd` -l$(LIBRARY)

# The first 'target' specified becomes the default target, i.e.,
# the one if you type 'make' without specifying any target on the
# command line.
#
# $@ and $< are 'automatic' variables. $@ indicates the target of the
# rule (in this case, $(PROG)); $< indicates the first dependency (here, $(PROG).cc)

$(PROG): $(PROG).cc lib$(LIBRARY).a
	$(CC) -o $@ $< $(LDFLAGS)

# This target specifies how to create the library starting from the (compiled) sources.
# $^ is again an automatic variable indicating 'all dependencies', i.e.,
# each time all sources will be re-added to the library

lib$(LIBRARY).a: $(OBJECTS)
	ar r $@ $^

# Finally, we need to specify how the object files are obtained from the sources.
# We do this using an implicit rule.
# The dependence on the header files is to ensure consistency: unless it is known
# for each source what headers it includes, we recompile everything if any header
# file changes. This is inefficient... but at least, we still save time in case
# only a source file changes.

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

