Programming in C

(Barry) #1
Debugging Programs with gdb 395

#ifdef DEBON


define DEBUG(level, fmt, ...) \


if (Debug >= level) \
fprintf (stderr, fmt, __VA_ARGS__)
#else


define DEBUG(level, fmt, ...)


#endif


When compiling a program containing the previous definition (which you can conve-
niently place inside a header file and include in your program), you either define DEBON
or not. If you compile prog.cas follows:


$ gcc prog.c


it compiles in the null definition for DEBUGbased on the #elseclause shown in the pre-
vious preprocessor statements. On the other hand, if you compile your program like this:


$ gcc –D DEBON prog.c


the DEBUGmacro that calls fprintfbased on the debug level is compiled in with the rest
of your code.
At runtime, if you have compiled in the debugging code, you can select the debug
level. As noted, this can be done with a command-line option as follows:


$ a.out –d3


Here, the debug level is set to 3. Presumably, you would process this command-line argu-
ment in your program and store the debug level in a variable (probably global) called
Debug.And in this case, only DEBUGmacros that specify a level of 3 or greater cause the
fprintfcalls to be made.
Note that a.out -d0sets the debugging level to zero and no debugging output is
generated even though the debugging code is still in there.
To summarize, you have seen here a two-tiered debugging scheme: Debugging code
can be compiled in or out of the code, and when compiled in, different debugging levels
can be set to produce varying amounts of debugging output.


Debugging Programs with gdb


gdbis a powerful interactive debugger that is frequently used to debug programs com-
piled with GNU’s gcccompiler. It allows you to run your program, stop at a predeter-
mined location, display and/or set variables, and continue execution. It allows you to
trace your program’s execution and even execute it one line at a time.gdbalso has a
facility for determining where core dumpsoccur. A core dump occurs due to some abnor-
mal event, possibly division by zero or attempts to access past the end of an array.This
results in the creation of a file named core that contains a snapshot of the contents of the
process’s memory at the time it terminated.^1


1.Your system might be configured to disable the automatic creation of this corefile, often due to
the large size of these files. Sometimes, this has to do with the maximum file creation size, which
can be changed with the ulimitcommand.

Free download pdf