114Chapter4 • Using GNU make
all: $(TARGETS)
# Rule to build object files
$(OBJS): $(SRCS)
$(CC) $(CFLAGS) -c $(@:.o=.c)
# Rules to build individual targets
ftp: $(FTPOBJS) $(FTPHDRS)
$(CC) $(LDFLAGS) $(FTPOBJS) -o ftp
tftp: $(TFTPOBJS) $(TFTPHDRS)
$(CC) $(LDFLAGS) $(TFTPOBJS) -o tftp
dnsresolver: $(DNSRESOLVEROBJS) $(DNSRESOLVERHDRS)
$(CC) $(LDFLAGS) $(DNSRESOLVEROBJS) -o dnsresolver
clean:
rm -f $(TARGETS) $(OBJS)
install:
cp $(TARGETS) $(INSTALLDIR)
# Additional Dependencies
ftp.o: $(FTPHDRS) tftp.o: $(TFTPHDRS)
dnsresolver.o: $(DNSRESOLVERHDRS)
After comments in the start of the makefile, the first part of the file defines variables used
in this file. As you shall see, defining variables is very helpful if you need any modification in
the Makefile or want to add or remove more files later on. After defining variables, the default
target is defined with the name "all" as follows:
all: $(TARGETS)
This in turn has dependencies on the three targets that we want to
make
. Please note that
we don't have any command to build this default target. When
make
reaches the default target, it
tries to meet dependencies to make sure that these are up-to-date. If any of these dependencies is
not up-to-date,
make
will try to recreate it.
The three dependencies to the default target (
ftp
,
tftp
and
dnsresolver
) have their
own rules to build. For example, the following ftp rule shows that it depends upon two variables
$(FTPOBJS)
and
$(FTPHDRS)
.
ftp: $(FTPOBJS) $(FTPHDRS)
$(CC) $(LDFLAGS) $(FTPOBJS) -o ftp
This means that if any of the files listed in these two variables has changed, the
ftp
tar-
get will be rebuilt. These files defined in the two variables are as follows: