A Makefile specifies rules. Each rule consits of:
Targets: A target is something that represents either a task we wish to automate or the name of a file we wish to generate. For example, most Makefiles have a target called "install". You specify the target on the invokation of make.
Command: Each target name has a sequence of shell commands associated with it. If the target is a file, the command will be something that generates that file ( such as a compile or link command ). If the target is something more abstract ( such as "install" ), then command will be a short shellscript that performs a certain function ( for example, installs a package )
Dependencies:
Each target has certain dependencies. The dependencies may be files
or other projects. When the user requests a certain target be
made, by invoking
make target
make checks that dependencies for target are
met, and executes commands for appropriate targets if
necessary, prior to attempting to run the command
for target.
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)
Makefiles have the following basic format:
VARIABLE1=value1 VARIABLE2=value2 target: dependency1 dependency2 command1 command2
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.cSo $@ matches the target, $< matches the dependency. $* matches the stem ( in the above case, file ).
Add an install target to the above Makefile.