Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help
next up previous contents
Next: Debugging Up: Source File organisation Previous: Multiple Source Files   Contents

Make

If you have many source files you don't need to recompile them all if you only change one of them. By writing a makefile that describes how the executable is produced from the source files, the make command will do all the work for you. The following makefile says that pgm depends on two files a.o and b.o, and that they in turn depend on their corresponding source files (a.c and b.c) and a common file incl.h:
   pgm: a.o b.o
       cc -Aa a.o b.o -o pgm
   a.o: incl.h a.c
       cc -Aa -c a.c
   b.o: incl.h b.c
       cc -Aa -c b.c
Lines with a `:' are of the form
target : dependencies
make updates a target only if it's older than a file it depends on. The way that the target should be updated is described on the line following the dependency line (Note: this line needs to begin with a TAB character).

Here's a more complex example of a makefile for a program called dtree. First some variables are created and assigned. In this case typing `make' will attempt to recompile the dtree program (because the default target is the first target mentioned). If any of the object files it depends on are older than their corresponding source file, then these object files are recreated.

The targets needn't be programs. In this example, typing `make clean' will remove any files created during the compilation process.

# Makefile for dtree
DEFS =  -Aa -DSYSV
CFLAGS = $(DEFS) -O
LDFLAGS = 
LIBS = -lmalloc -lXm -lXt -lX11 -lm

BINDIR = /usr/local/bin/X11
MANDIR = /usr/local/man/man1

OBJECTS_A = dtree.o Arc.o Graph.o 	#using XmGraph

ARCH_FILES = dtree.1 dtree.c Makefile Dtree Tree.h TreeP.h \
   dtree-i.h Tree.c Arc.c Arc.h ArcP.h Graph.c Graph.h GraphP.h

dtree: $(OBJECTS_A)
        $(CC) -o dtree $(LDFLAGS) $(OBJECTS_A) $(LIBS)

Arc.o:	Arc.c
        $(CC) -c $(CFLAGS) Arc.c

Graph.o:	Graph.c
        $(CC) -c $(CFLAGS) Graph.c

dtree.o:	dtree.c
        $(CC) -o dtree.o -c $(CFLAGS) -DTREE dtree.c

install: dtree dtree.1
        cp dtree $(BINDIR)
        cp dtree.1 $(MANDIR)

clean:
        rm -f dtree *.o core tags a.out


next up previous contents
Next: Debugging Up: Source File organisation Previous: Multiple Source Files   Contents
Tim Love 2010-04-27