Programming in C

(Barry) #1
Other Utilities for Working with Larger Programs 343

want to learn how to use.These tools are not part of the C language. However, they can
help speed your development time, which is what it’s all about.
Following is a list of tools you might want to consider when working with larger
programs. If you are running Unix, you will find a plethora of commands at your dispos-
al that can also help you in your development efforts.This is just the tip of the iceberg
here. Learning how to write programs in a scripting language, such as the Unix shell, can
also prove useful when dealing with large numbers of files.


The makeUtility


This powerful utility (or its GNU version gnumake) allows you to specify a list of files
and their dependencies in a special file known as a Makefile.The makeprogram automat-
ically recompiles files only when necessary.This is based on the modification times of a
file. So, if makefinds that your source (.c) file is newer than your corresponding object
(.o) file, it automatically issues the commands to recompile the source file to create a
new object file.You can even specify source files that depend on header files. For exam-
ple, you can specify that a module called datefuncs.ois dependent on its source file
datefunc.cas well as the header file date.h.Then, if you change anything inside the
date.hheader file, the makeutility automatically recompiles the datefuncs.cfile.This
is based on the simple fact that the header file is newer than the source file.
Following is a simple Makefilethat you could use for the three-module example
from this chapter. It is assumed here that you’ve placed this file in the same directory as
your source files.


$ cat Makefile
SRC = mod1.c mod2.c main.c
OBJ = mod1.o mod2.o main.o
PROG = dbtest


$(PROG): $(OBJ)
gcc $(OBJ) -o $(PROG)


$(OBJ): $(SRC)


A detailed explanation of how this Makefileworks is not provided here. In a nutshell, it
defines the set of source files (SRC), the corresponding set of object files (OBJ), the
name of the executable (PROG), and some dependencies.The first dependency,


$(PROG): $(OBJ)


says that the executable is dependent on the object files. So, if one or more object files
change, the executable needs to be rebuilt.The way to do that is specified on the follow-
ing gcccommand line, which must be typed with a leading tab, as follows:


gcc $(OBJ) -o $(PROG)

The last line of the Makefile,


$(OBJ): $(SRC)

Free download pdf