Using Variables119
You can modify this file so that it uses implicit rules to build object files. The modified file
is shown below:
# Variable definition
OBJS = ftp.o common.o
HDRS = ftp.h common.h
CFLAGS = -g -O2
TARGETS = ftp
CC = gcc
# Default Target
ftp: $(OBJS) $(HDRS)
$(CC) $(OBJS) -o ftp
clean:
rm -f $(TARGETS) $(OBJS)
Note that we have completely taken out two rules that are used to build the object files.
Now when
make
needs to build these object files, it uses its implicit rule for this purpose. Run-
ning
make
on this makefile produces the following result.
[root@conformix make]# make
gcc -g -O2 -c -o ftp.o ftp.c
gcc -g -O2 -c -o common.o common.c
gcc ftp.o common.o -o ftp
[root@conformix make]#
Note that the first two lines of the output create object files using implicit rules. You may
also have noted that the
CFLAGS
variable is also used in this process. Like
CFLAGS
, implicit
rules use other variables while building targets. For a more detailed discussion, please see the
reference at the end of this chapter.
While using implicit rules, you should be careful about the process, because
make
can
build a target using explicit rule depending upon which source files are available. For example,
make
can produce an object file from a C source code file as well as Pascal source code file. In
the above example, if
common.c
file is not present but
common.p
(Pascal source code file) is
present in the current directory,
make
will invoke Pascal compiler to create
common.o
file,
which may be wrong. You also have less control over options on implicit rules.
4.3Using Variables
Variables are an important part of all makefiles used in a project. Variables are used for many
purposes; the most important of which is to have structured and easily understandable makefiles.
This section contains more information about variables used in makefiles.