Programming in C

(Barry) #1

394 Chapter 18 Debugging Programs


Program 18.3 Output
$ gcc pre3.c
$ a.out 8 12
processed 2 arguments
arg1 = 8, arg2 = 12
process (8, 12)
return 96
96

As you can see, the program is much more readable in this form.When you no longer
need debugging output, simply define the macro to be nothing:
#define DEBUG(fmt, ...)
This tells the preprocessor to replace calls to the DEBUGmacro with nothing, so all uses
of DEBUGsimply turn into null statements.
You can expand on the notion of the DEBUGmacro a little further to allow for both
compile-time and execution-time debugging control: Declare a global variable Debug
that defines a debugging level. All DEBUGstatements less than or equal to this level pro-
duce output.DEBUGnow takes at least two arguments; the first is the level:
DEBUG (1, "processed data\n");
DEBUG (3, "number of elements = %i\n", nelems)
If the debugging level is set to 1 or 2, only the first DEBUGstatement produces output; if
the debugging level is set to 3 or more, both DEBUGstatements produce output.The
debugging level can be set via a command-line option at execution time as follows:
a.out –d1 Set debugging level to 1
a.out -d3 Set debugging level to 3
The definition for DEBUGis straightforward:
#define DEBUG(level, fmt, ...) \
if (Debug >= level) \
fprintf (stderr, fmt, __VA_ARGS__)
So
DEBUG (3, "number of elements = %i\n", nelems);
becomes
if (Debug >= 3)
fprintf (stderr, "number of elements = %i\n", nelems);
Again, if DEBUGis defined to be nothing, the DEBUGcalls become null statements.
The following definition provides all the mentioned features, as well as the ability to
control the definition of DEBUGat compile time.
Free download pdf