Groovy hepcat FBM was jivin' on 29 Apr 2006 21:47:45 -0700 in
comp.lang.c.
#iidef and #define to debug program's a cool scene! Dig it!
I am preparing project for submission and i'd like to allow the print
out of debug messages. I know that with something like
#define DEBUG
#ifdef DEBUG
print(X);
#endif
you can print out comments in an effective way.. however, can these
#define be sent through the command line, in form of a paramterer?
Sure, it's easy. I mean, you can't do it this way, of course. This
way is done at compile time. However, you can write a function that
can be switched on or off by a command line argument.
Create a new C source file containing something like the follwing
code:
#include <stdio.h>
#include <stdarg.h>
#include "debug.h"
static int debug_on = DBG_OFF;
void dbg_enable(int on_off)
{
debug_on = on_off;
}
int dbg_printf(const char *fmt, ...)
{
va_list ap;
int r = 0;
if(DBG_OFF != debug_on)
{
va_start(ap, fmt);
r = vfprintf(stderr, fmt, ap);
va_end(ap);
}
return r;
}
Save this as debug.c or something similar. Now, create another new C
source file, put the following code in it, and save it as debug.h or
similar:
#ifndef DEBUG_H
#define DEBUG_H
#define DBG_OFF 0
#define DBG_ON 1
void dbg_enable(int on_off);
int dbg_printf(const char *fmt, ...);
#endif
Now, in all your C source files in which you need this
functionality, include debug.h by putting the following line someplace
near the top of the file:
#include "debug.h"
You'll also have to compile and link debug.c with the rest of your
program. (See your compiler documentation for information on how to do
this.)
In your main() function, when you check for command line arguments,
if you find the argument to turn debugging on, you can easily do so by
passing DBG_ON to dbg_enable(). Then you call dbg_printf() to write
your debug messages. For example:
#include <stdio.h>
#include <string.h>
#include "debug.h"
int main(int argc, char **argv)
{
if(1 < argc && 0 == strcmp(argv[1], "-debug"))
{
dbg_enable(DBG_ON);
}
dbg_printf("Testing %d, %d, %d...\n", 1, 2, 3);
return 0;
}
--
Dig the even newer still, yet more improved, sig!
http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?