CS308: Using Simple Makefiles


Here is a simple makefile:

CCC = CC
CCFLAGS = -g +w

driver: driver.o queue.o
	${CCC} ${CCFLAGS} -o driver.out driver.o queue.o

driver.o: driver.cc queue.h stdinc.h
	${CCC} ${CCFLAGS} -c driver.cc

queue.o: queue.cc queue.h stdinc.h
	${CCC} ${CCFLAGS} -c queue.cc

The first line indicates to use CC for the compiler. The second line provides the flags for CC. To learn about the possibile flags available see the CC manpage using "man CC". Some useful flags are "-g" to add necessary informtion to be used by the debugger, "+w" to have the compiler give extra warning messages about questionable constructs, "-o filename" to provide a filename for the output (versus the default of a.out), and "-c" to indicate that no linking should be performed (and thus this is used to generate the object files).

The remaining pairs of lines each have the form:

 target : prerequisites
	the command that generates the target 

where the prerequisites are all the files that are used in generating the target. Note that it is essential that the second line begins with a tab.

In our example makefile above, the first pair of lines says that to create the executable for driver it will use driver.o and queue.o. Thus if either of these files have been updated more recently than driver.out then the command

 CC -g -o driver.out driver.o queue.o 
should be run. This command links the object files driver.o and queue.o to create the executable driver.out. Then to run the program you can type "driver.out" in your unix shell.

The second pair of lines in our example makefile indicate that to create the object file for driver (driver.o) it depends on driver.cc, queue.h, and stdinc.h. If any of these files have changed more recently than driver.o then the command

 CC -g +w -c queue.cc
which will recompile queue.cc to obtain the new object file queue.o.

Finally, to use the makefile simple type "make driver". As a default if you just type "make" it will make the first target given.