Programming Utilities Guide

Compiling Debugging and Profiling Variants

The following makefile produces optimized, debugging, or profiling variants of a C program, depending on which target you specify (the default is the optimized variant). Command dependency checking guarantees that the program and its object files will be recompiled whenever you switch between variants.

Table 4-11 Makefile for a C Program with Alternate Debugging and Profiling Variants
# Makefile for a C program with alternate 
# debugging and profiling variants.  

CFLAGS= -O 

.KEEP_STATE:

all debug profile: functions 

debug := CFLAGS = -g 
profile := CFLAGS = -pg -O 

functions: main.o data.o 
       	$(LINK.c) -o $@ main.o data.o -lcurses
        -ltermlib 
lint: main.ln data.ln 
       	$(LINT.c) main.ln data.ln 
clean: 
       	rm -f functions main.o data.o main.ln data.ln

The first target entry specifies three targets, starting with all.


Note -

Debugging and profiling variants are not normally considered part of a finished program.


all traditionally appears as the first target in makefiles with alternate starting targets (or those that process a list of targets). Its dependencies are "all" targets that go into the final build, whatever that might be. In this case, the final variant is optimized. The target entry also indicates that debug and profile depend on functions (the value of $(PROGRAM)).

The next two lines contain conditional macro definitions for CFLAGS.

Next comes the target entry for functions. When functions is a dependency for debug, it is compiled with the -g option.

The next example applies a similar technique to maintaining a C object library.

Table 4-12 Makefile for a C Library with Alternate Variants
# Makefile for a C library with alternate 
# variants.  

CFLAGS= -O 

.KEEP_STATE
.PRECIOUS:  libpkg.a

all debug profile: libpkg.a 
debug := CFLAGS= -g 
profile := CFLAGS= -pg -O 

libpkg.a: libpkg.a(calc.o map.o draw.o) 
         	ar rv $@ $? 
         	libpkg.a(%.o): %.o 
         	@true 
lint: calc.ln map.ln draw.ln 
         	$(LINT.c) calc.ln map.ln draw.ln 
clean: 
         	rm -f libpkg.a calc.o map.o draw.o \
          calc.ln map.ln draw.ln