Computer Science Help Center
Debugging Techniques
Use of the Pre-processor #define Statements
This concept can be improved, building off of the previous example. Say there are a lot of debugging print statements in the source code. Wouldn't it be nice to be able to turn them all on or off quickly, rather that commenting each and every one on and off. Well this can be done easily...

Source Code Before:
#include <stdio.h>

int main()
{
   int array[10];
   int i;


   for (i = 0 ; i < 20 ; i++)
   {
#ifdef DEBUG_ON
printf("In for loop: i = %d\n", i);
#endif
      array[i]=1;
   }

   for (i = 0 ; i < 10 ; i++)
   {
      printf("%d", array[i]);
   }

   return 0;
}
Compilation & Execution Before:
linux1[37]% gcc -ansi -Wall main.c
linux1[38]% a.out 
Segmentation fault (core dumped)
linux1[39]%
"#ifdef DEBUG_ON" and "#endif" have been added around all of the print statements. Basically this tells the pre-processor, if "DEBUG_ON" has been defined, do include what is between the "#ifdef" and "#endif" statements. "DEBUG_ON" could be anything, but as with any code, use something logical. In the above example "DEBUG_ON" has not been defined, and the output shows no change.
 
Source Code After:
#include <stdio.h>
#define DEBUG_ON

int main()
{
   int array[10];
   int i;


   for (i = 0 ; i < 20 ; i++)
   {
#ifdef DEBUG_ON
printf("In for loop: i = %d\n", i);
#endif
      array[i]=1;
   }

   for (i = 0 ; i < 10 ; i++)
   {
      printf("%d", array[i]);
   }
 
   return 0;
}
Compilation & Execution After:
linux1[40]% gcc -ansi -Wall main.c
linux1[41]% a.out
In for loop: i = 0
In for loop: i = 1
In for loop: i = 2
In for loop: i = 3
In for loop: i = 4
In for loop: i = 5
In for loop: i = 6
In for loop: i = 7
In for loop: i = 8
In for loop: i = 9
In for loop: i = 10
In for loop: i = 11
In for loop: i = 12
In for loop: i = 13
In for loop: i = 14
In for loop: i = 15
In for loop: i = 16
In for loop: i = 17
In for loop: i = 18
In for loop: i = 19
Segmentation fault (core dumped)
linux1[42]% 
With "#define DEBUG_ON" placed in the source code, the pre-processor will recognize "DEBUG_ON" as being defined, and will include all statements nested within the "#ifdef" and "#endif" pre-processor directives.
 
Notes:
Multiple "#define" statements
Multiple #define statements can be used to print multiple levels of debugging information.
"#define DEBUG_LEVEL_1" might only print when calling a function... "in Foo()"
"#define DEBUG_LEVEL_2" might print what values are passed in... "calling Foo( x=1, y=2 )" etc...
It would be necessary to have each #ifdef check for the appropriate level.



Modified by: Dawn Block, September 2003
Created by: Daniel J. Hood, February 2000
http://www.csee.umbc.edu/~cshc/resources/debug/defines.shtml
Sunday, 10-Sep-2006 15:32:02 EDT