#define DEBUG 1

As a response to your problem you can also simply invoke the compiler like:

cc -c -DDEBUG=1 

or

 cc -c -DDEBUG=0

You must delete the "define DEBUG 1/0" in your files - or replace it with:

#ifndef DEBUG
#define DEBUG 0
#endif

Here is what I am using (GCC syntax):

  • create a file debug.h with the following content and include it in each c file:

    #ifdef DEBUG
    extern FILE *dbgf;
    #define D_MIN   0x00010000  // Minimum level
    #define D_MED   0x00020000  // Medium level
    #define D_MAX   0x00040000  // Maximum level 
    #define D_FLUSH 0x00080000  // Usefull by a program crash
    #define D_TRACE 0x00100000  
    #define D_1     0x00000001  
    ...
    
    #define D(msk, fmt, args...) if(msk & dbgmsk) { fprintf(dbgf, "%s:",__FUNCTION__); fprintf(dbgf, fmt, ## args ); if(msk & D_FLUSH) fflush(dbgf); }
    #define P(msk, fmt, args...) if(msk & dbgmsk) { fprintf(dbgf, fmt, ## args ); if(msk & D_FLUSH) fflush(dbgf); }
    
    #else
    #define D(msk, fmt, args...)
    #define P(msk, fmt, args...)
    #endif
    

dbgmsk is variable, which can be global (whole program) or local/static and must be initialized a start. You can define several options for the whole program or for each module. This is better and more flexible than the version with the level variable.

Ex. module1.c:

#include "debug.h"

static int dbgmsk;  // using local dbgmsk
module1_setdbg(int msk) { dbgmsk = msk; D(D_TRACE,"dbgmsk1=%x\n", dbgmsk); }

foo1() {  P(D_1, "foo1 function\n" ); 
  ....
}
foo2() {}
...

foo3.c

#include "debug.h"
extern int dbgmsk; // using global dbgmsk

Ex. main:

#include "debug.h"
FILE *dbgf;
int dbgmsk = 0; // this is the global dbgmsk

int main() { 
  dbgf = stderr; // or your logfile
  dbgmsk = D_MIN;
  module1_setdbg(D_MIN|D_MED|D_TRACE|D_1);
  ....
}

I'm also storing all dbgmsk variables in a config text file that is read at the program start.


Try something like Steve McConnel suggests in section 6 of "Chapter 8: Defensive Programming" from Code Complete 2... Add this to your code:

#ifdef DEBUG
#if (DEBUG > 0) && (DEBUG < 2)
printf("Debugging level 1");
#endif

#if (DEBUG > 1) && (DEBUG < 3)
printf("Debugging level 2");
#endif

#if (DEBUG > n-1) && (DEBUG < n)
printf("Debugging level n");
#endif
#endif

Then when you compile, add this flag (warning: This might be compiler-dependent):

-DDEBUG=m

Or, have a global header that defines these sorts of things, as others have suggested.


When compiling, you should be able to specify an option to your compiler. For example, you can call GCC with the -DDEBUG option.

In this case, you would be better using:

#ifdef DEBUG
#endif

or:

#if defined(DEBUG)
#endif

if this is not the way you're doing it now. I'm surprised that you don't have a global header file for your project. Something along the lines of:

#undef DEBUG
#define DEBUG 1

in a file called "debug.h". In your C programs, you can include this by using #include "debug.h"

Tags:

C

Debugging