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?
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With