Make

The Problem

make solves these problems. It is a build automation tool.

The Model

A Makefile specifies rules. Each rule consits of:

Variables

It simplifies things greatly if one uses variables. Makefile permits the use of variables. They are defined with the syntax
VAR=VALUE
And dereferenced with the syntax
$(VAR)

The format of a Makefile

Makefiles have the following basic format:


VARIABLE1=value1
VARIABLE2=value2

target:	dependency1 dependency2 
	command1
	command2

Sample Makefile

You may download this example.


CXX=g++
PROG=test
INCLUDES=
LD_FLAGS=
SOURCES=test.cpp bar.cc
OBJS=test.o bar.o

%.o:	%.cpp
	$(CXX) -o $@ -c $(INCLUDES) $<

%.o:	%.cc
	$(CXX) -o $@ -c $(INCLUDES) $<

$(PROG): $(OBJS)
	$(CXX) -o $(PROG) $(OBJS) $(LD_FLAGS)

In fact the above Makefile is a good boiler-plate for simple projects, since the compile commands are all expressed in terms of the variables. Some of the rules need explaining. Let's examine them:

%.o:    %.cc
    $(CXX) -o $@ -c $(INCLUDES) $<  

This creates a rule for each pair of files with .cc and .o extensions that looks like this:

file.o:
	$(CXX) -o file.o -c $(INCLUDES) file.c

So $@ matches the target, $< matches the dependency. $* matches the stem ( in the above case, file ).

Exercise

Add an install target to the above Makefile.