8. Makefiles
If the source consists of a single source file (e.g. foo.c, it can be compiled straightforward with
gcc -o foo foo.c
However, most applications consist of several / many source (and header) files. Moreover, there are sometimes complicated dependencies as to which files need to be re-compiled if some file has been edited. For this reason, there is a utility called make that allows to build large and complex applications simply by specifying appropriate rules in a Makefile, and then invoking make.
![]() | NOTE |
|---|---|
If there is no Makefile, but a file named Makefile.in, then there is usually also a file named configure. Read Section 9> to learn how to create a Makefile from these files. |
8.1. Syntax of a Makefile
A Makefile contains a number of rules. Each of these rules has on the first line a target (that should be made by the rule), followed by a colon, optionally followed by a list of dependencies (that are required to make the target). Optionally, the next line(s) contain the (shell) command(s) to make the target. Each of these lines must start with a tab — not some spaces.
If make is invoked, you can give any target in the makefile as argument. The default target is "all" (that is, a target named "all", not all targets). Also, by default make will use a file named Makefile in the current directory. Thus, we can create a file Makefile with two targets "all" and "foo" like this:
all: foo
foo: foo.c
gcc -c foo foo.c
We can then invoke make like this:
bash$ make
gcc -c foo foo.c
bash$ make foo
make: `foo' is up to date.
bash$ make nonexistent_target
make: *** No rule to make target `nonexistent_target'. Stop.
(The first command will make "all", which will also cause
"foo" to be made (because the rule for "all"
requires "foo"). The second command will do nothing, because
"foo" has just been made, and "foo.c" has not
been changed since. The third command fails because we have no
rule for "nonexistent_target" in our example
Makefile).
Commonly, a Makefile has rules for targets like
- all
Default target, usually compiles the application.
- install
Installs the compiled application, and eventually manpages or other files required to use the application.
- uninstall
Uninstalls the application.
- clean
Removes intermediary files generated during the compilation of the application.
- distclean
Removes anything generated during the compilation, to start allow a fresh start.
