Programming in C

(Barry) #1

392 Chapter 18 Debugging Programs


fprintf (stderr, "return %i\n", val);
#endif
return val;
}

int main (int argc, char *argv[])
{
int arg1 = 0, arg2 = 0;

if (argc > 1)
arg1 = atoi (argv[1]);
if (argc == 3)
arg2 = atoi (argv[2]);
#ifdef DEBUG
fprintf (stderr, "processed %i arguments\n", argc - 1);
fprintf (stderr, "arg1 = %i, arg2 = %i\n", arg1, arg2);
#endif
printf ("%i\n", process (arg1, arg2));

return 0;
}

Program 18.2 Output
$ gcc –D DEBUG p18-2.c Compile with DEBUG defined
$ a.out 5 10
processed 2 arguments
arg1 = 5, arg2 = 10
process (5, 10)
return 50
50

Program 18.2 Output (Rerun)
$ gcc p18-2.c Compile without DEBUG defined
$ a.out 2 5
10

When the program is ready for distribution, the debugging statements can be left in the
source file without affecting the executable code, as long as DEBUGisn’t defined. If a bug
is found at some later time, the debugging code can be compiled in and the output
examined to see what’s happening.
The previous method is still rather clumsy because the programs themselves tend to
be difficult to read. One thing you can do is change the way the preprocessor is used.

Program 18.2 Continued
Free download pdf