Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define DEBUG 1

Tags:

c

debugging

I'm trying to have a debugging mode on so if

#define DEBUG 1 

I want to printf some variable values and if

#define DEBUG 0 

I want them off.

The problem is I have many implementation files and I want this DEBUG variable to be available for the whole project. Right now I need to edit the DEBUG variable in foo1.c, foo2.c, foo3.c which seems tedious and error-prone and there must be a better way. Any suggestions?

like image 588
Stu Avatar asked Jun 12 '09 16:06

Stu


2 Answers

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"

like image 50
Lucas Jones Avatar answered Sep 17 '22 01:09

Lucas Jones


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.

like image 33
Pete Avatar answered Sep 19 '22 01:09

Pete