Breder.org

The Basics of GNU Make

A quick guide on getting started with the GNU Make tool and using Makefiles to specify build targets and build dependencies. The make command is commonly used in Linux/Unix environments for building programs from source, but can also be applied for building derivative documents.

GNU Make is a tool intended for building executables from its binary and source dependencies.

More concretely, you specify the dependency tree between generated and source files on a Makefile, and GNU Make takes care of rebuilding the needed files as needed, when their sources are modified.

It also allow you to group shell commands with a more friendly name. For example, instead of having a directory full of shell scripts, you can have a single Makefile and call the same shell commands through, for example, make clean.

Makefile format

A Makefile is simply a text file named Makefile and placed in the root of your project. When the make command is called, it will look for it and act as instructed.

A Makefile is composed of targets, dependencies and shell commands, as shown below:

target: dependency1 dependency2 ... dependency3
	command1
	command2
	...
	commandM

The target is either a friendly label or the path to an specific path of a file which is built through the commands listed below. The dependencies are other targets which should be built first, that is, targets which the present target depends upon.

When the make command is called without arguments, the first target is built. When it is called make [target], the particular target is built (and all of its dependencies, as needed).

Using variables in Makefiles

A variable may be specified as follows:

variable_name = file1 file2 ... fileN

It can then be referred in recipes as follows:

target : $(var1)
	some-shell-command $(var2)

$(var3) : dep1 dep2 ... depN
	command1
	...
	commandM

Using result of shell command

You can use a special $(shell ...) function to use the value of the output of the shell command. For example:

today:
	touch notes-$(shell date --iso).md

This will generate a file such as notes-2022-03-28.md, running the shell command date --iso to get today's date in the ISO format (YYYY-MM-DD).

Automatic variables

Variables from environment

From the manual: “Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value.”

Environment variables may be overridden by passing an -e option through command-line arguments.

More Resources