Programming in C

(Barry) #1
Debugging with the Preprocessor 391

fprintfs never make it to the compiler (they’re removed from the program by the pre-
processor). As you can see, the program prints out messages after it reads in the integers.
The second time the program is run, an invalid character is entered (e).The debugging
output informs you of the error. Note that to turn off the debugging code, all you have
to do is remove the line


#define DEBUG

and the fprintfs are not compiled with the rest of the program. Although this program
is so short you might not feel it’s worth the bother, consider how easy it is to turn
debugging code on and off in a program several hundreds of lines long by simply chang-
ing one line.
You can even control the debugging from the command line when the program is
compiled. If you’re using gcc, the command


gcc –D DEBUG debug.c

compiles the file debug.c, defining the preprocessor variable DEBUGfor you.This is
equivalent to putting the following line in your program:


#define DEBUG

Ta ke a look at a slightly longer program. Program 18.2 takes up to two command-line
arguments. Each of these is converted into an integer value and is assigned to the corre-
sponding variables arg1and arg2.To convert the command-line arguments into inte-
gers, the standard library function atoiis used.This function takes a character string as
its argument and returns its corresponding representation as an integer.The atoifunc-
tion is declared in the header file <stdlib.h>, which is included at the beginning of
Program 18.2.
After processing the arguments, the program calls the processfunction, passing the
two command-line values as arguments.This function simply returns the product of
these two arguments. As you can see, when the DEBUGidentifier is defined, various
debugging messages are printed, and when it isn’t defined, only the result is printed.


Program 18.2 Compiling in Debug Code


#include <stdio.h>
#include <stdlib.h>


int process (int i1, int i2)
{
int val;


#ifdef DEBUG
fprintf (stderr, "process (%i, %i)\n", i1, i2);
#endif
val = i1 * i2;
#ifdef DEBUG

Free download pdf