main.d
and array.d
. But they are only
informational up to this point. We can, indeed, include them in the
Makefile:
CC = gcc # g++ for c++ programs CXXFLAGS = -O -Wall -g LDFLAGS = -g SRC = main.c array.c EXE = main $(EXE): $(SRC:.c=.o) #array.o: array.c array.h # gcc $(CXXFLAGS) -c array.c #main.o: main.c array.h # gcc $(CXXFLAGS) -c main.c %.d: %.c set -e; gcc $(CXXFLAGS) $^ -MM \ | sed 's/\($*\)\.o[ :]*/\1.o $@ : /g' > $@; \ [ -s $@ ] || rm -f $@ clean: rm -f $(EXE) $(CSRC:.c=.o) $(CSRC:.c=.d) include $(SRC:.c=.d)
Here, the statement ``include $(SRC=.c=.d)
is saying
for each source file listed in SRC
, include its .d
(dependency) file. Because these files already specify that
array.o
depends on array.c
and array.h
,
there is no need to explicitly state that rule anymore. The
#
symbol states that whatever follows on the same line
should be ignored.
Now, go ahead and update array.h
, then run make
again.
We only have one problem now: cc
is used as our compiler, not
gcc
. This is because the rules included in main.d
and
array.d
only state the dependency, but not the command to
generate the .o
files. This leaves everything to the default
settings, which uses cc
to compile C programs. On most systems,
cc
is a ``shortcut'' (symlink) to gcc
.
Note that the variable CC
specifies the compiler to use.
By default, the program cc
is used. You can change
the definition of CC
to gcc
for C programs, or
g++
for C++ programs. You can even specify a particular
version of compiler, such as gcc-3.1
.
The variable LDFLAGS
is similar to to CXXFLAGS
, but
instead of specifying compile-time flags, it specifies link time
flags. Here we only specify -g
to include debug information
in the executable.
The variables CC
, CXXFLAGS
and LDFLAGS
are
special because they are used by the default Makefile rules. You
need to use these specific names if implicit rules (like those contained
in .d
files) are used.
The special target clean
is used if you want to delete
all the created files.
Copyright © 2006-10-08 by Tak Auyeung