Getting started with make

Make is a Unix tool to order operations used in the construction of programs.

-----

Why use make?

-----

What does make do?

Make takes

and works out what steps are necessary to get from the available ingredient files to the desired output.

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.

-----

A simple makefile

This makefile is used to build a simple game. The diagram below shows the structure of the makefile:

Example: building files from other files

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.

-----

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.

A makefile with variables

-----

Pattern Rules

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.

Special variables: ‘$<’ and ‘$@

$*’ (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.

A makefile with pattern rules

-----

Cleaning up afterwards

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.

A makefile with clean

-----

Functions

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.

Other related tools