Programming in C

(Barry) #1

18 Debugging Programs


18 Debugging Programs


THIS CHAPTER TEACHES YOU TWO TECHNIQUESyou can use to debug your programs.
One involves using the preprocessor to allow for the conditional inclusion of debugging
statements in your program.The other technique involves the use of an interactive
debugger. In this chapter, you are introduced to a popular debugger called gdb.Even if
you use a different debugger (such as dbx, or one built in to an IDE tool), it is likely that
your debugger will have similarities to gdb.


Debugging with the Preprocessor


As noted in Chapter 13, “The Preprocessor,” conditional compilation is useful when
debugging programs.The C preprocessor can be used to insert debugging code into
your program. By appropriate use of #ifdefstatements, the debugging code can be
enabled or disabled at your discretion. Program 18.1 is a program (admittedly contrived)
that reads in three integers and prints out their sum. Note that when the preprocessor
identifier DEBUGis defined, the debugging code (which prints to stderr) is compiled
with the rest of the program, and when DEBUGisn’t defined, the debugging code is
left out.


Program 18.1 Adding Debug Statements with the Preprocessor


#include <stdio.h>
#define DEBUG


int process (int i, int j, int k)
{
return i + j + k;
}

Free download pdf