A common example is the target "all". This is often the first target in a makefile, and is usually just a list of dependencies which do the actual file building. For example, take the following makefile:
all: build install
build: myprog yourprog
myprog: mainfile.o math.o
cc -o myprog mainfile.o math.o
mainfile.o: mainfile.c
cc -c -o mainfile.o mainfile.c
math.o: math.c
cc -c -o math.o math.c
yourprog: yourfile.c
cc -o yourprog yourfile.c
install:
cp myprog /usr/local/bin/myprog
In this makefile, there are two programs to be built, "myprog"
and "yourprog". The targets "mainfile.o" and
"math.o" just build objects which are to be linked to form
"myprog". The target "install" is used to
place the programs in the proper place in the directory tree.
The targets we are interested in are "all" and "build". Let's look at "build" first. The rule for "build" is:
build: myprog yourprog
This rule causes "make" to update "myprog"
and "yourprog". In other words, it will cause
"myprog" and "yourprog" to be built. It is
simply a list of the targets we want updated. By entering the command
"make build
" at the shell prompt, we cause "make"
to build these two programs without us even knowing their names.
Notice that this rule doesn't have any commands, just a dependency list. Its entire purpose is to consolidate a set of targets to be built into one name.
Now, let's look at the rule for "all":
all: build install
We see that this rule also has no command section. It's purpose is to provide
a common target name to do everything that I (the user) might want the makefile
to do.
Typically, when you build a program, you want to install it somewhere, so why
not do it with one command? (Well, there are reasons, but sometimes they
aren't too important.) In this example, typing "make all
", will
cause the programs to be built via the "build" rule, then
installed via the "install" rule. With the
"all" rule, I only have to type one command.
It turns out that I don't even need to type "make all
". I could
just type "make
" and make will start with the
target "all" just as if I had typed "make all
".
This is because "make" takes the first target listed in the
makefile as its "default" target if no target is given on the
command line. This is why "all" is often listed as the first
target in a makefile.
If we just type "make
" at the command line, "make"
will scan through the makefile and find the first target; in this case,
"all". It will then start processing the rule for
"all" by processing each of its dependencies, each of their
dependencies, etc. So, using this makefile, the user can build and install the
programs "myprog" and "yourprog" without
knowing their names by simply entering "make
" at the command line.