Make is a Unix tool to order operations used in the construction of programs.
Make takes
When Informix was porting their database to Linux, they said “We just typed ‘make’”
Make, when used sensibly, can remove much of the work involved in maintaining huge projects.
This makefile is used to build a simple game. The diagram below shows the structure of the makefile:
If I save this file as ‘Makefile’, or ‘makefile’, or even ‘GNUMakefile’, then to build the entire project, I simply type make!
The all target is the default target (the default is
usually the first target in the file, but there are some special
rules — read the manual to find these out).
This file is quite long for the few files it refers to. This is because it explicitly states all the steps involved. Not only that, but each .o file includes the same set of headers. What we need is a way of setting and using variables.
Make provides a messy, but effective way to do variables. To use a variable we write $(VARIABLE). So, we can replace the headers in each line with a single variable. Then if a new header is added, we can simply update the variable definition at the top.
The previous example is still somewhat long, having a separate entry for each .o file. We can shorten it by using pattern rules.
The most convenient way to write a pattern rule in GNU make is with the % character as a sort of wildcard:
%.o: %.c game.h preferences.h
gcc -c $*.c -o $*.o
This means that any file whose name ends with .o can be built from a correspondingly-named .c file and the listed header files. In the command, ‘$*’ is a variable that will be replaced by whatever matched the % character in the dependency line (the “stem”).
Note that ‘%’ should be used in the dependency line, while ‘$*’ is used in the commands to be executed.
‘$*’ (see Pattern Rules) is the only special variable that you need to remember, and has a fairly straightforward meaning.
But there are two other variables that people usually use instead of
‘$*’. They are:
In GNU make, $< and $@ can be used in any rules, not just in pattern rules.
When making make files, it is a good idea to put in at least a
clean target. This target is used to remove all the
extra .o files and the compiled program.
Make has a large number of functions provided to manipulate
variables. In this last example
I’ve made every .h file in the project
to automatically be added to $(HEADERS), and all .c files, except editor.c, are built into the game.
#include other .h
files; can use checksums instead of timestamps; can use regular
expressions in pattern rules). However, its syntax is more verbose
than that of make.
There is a make2cook
utility to convert from existing makefiles.