M
Mark
Hello
I had to make some mechanism to turn on/off debugging messages at run-time
in various modules of a project. This is what I've come up with: I defined
several constants, each with exactly one bit set, and a global variable
which should be defined in a particular module and assigned with one or a
few values TAG_1...TAG_4:
/* debug.h */
#ifndef DEBUG_H
#define DEBUG_H
#include <stdio.h>
#define TAG_1 0x00000001
#define TAG_2 0x00000002
#define TAG_3 0x00000004
#define TAG_4 0x00000008
extern unsigned long debug_mask;
#define DEBUG(tag, fmt, arg) \
do { \
if (0 == ((~debug_mask) & (tag))) { \
printf(fmt, arg); \
} \
} while (0)
#endif /* DEBUG_H */
/* example of usage*/
#include "debug.h"
unsigned long debug_mask;
int main(void)
{
int i=1;
char p='c';
debug_mask = TAG_4 | TAG_2;
DEBUG(TAG_4, "i=%d\n", i);
DEBUG(TAG_2, "p=%c\n", p);
return 0;
}
Right now I need only one argument passed. It appears the macro works as
expected, or I have not spotted bugs yet.
Is there anything wrong with this simple implementation (especially bit
operations)? Any advices are welcome.
I had to make some mechanism to turn on/off debugging messages at run-time
in various modules of a project. This is what I've come up with: I defined
several constants, each with exactly one bit set, and a global variable
which should be defined in a particular module and assigned with one or a
few values TAG_1...TAG_4:
/* debug.h */
#ifndef DEBUG_H
#define DEBUG_H
#include <stdio.h>
#define TAG_1 0x00000001
#define TAG_2 0x00000002
#define TAG_3 0x00000004
#define TAG_4 0x00000008
extern unsigned long debug_mask;
#define DEBUG(tag, fmt, arg) \
do { \
if (0 == ((~debug_mask) & (tag))) { \
printf(fmt, arg); \
} \
} while (0)
#endif /* DEBUG_H */
/* example of usage*/
#include "debug.h"
unsigned long debug_mask;
int main(void)
{
int i=1;
char p='c';
debug_mask = TAG_4 | TAG_2;
DEBUG(TAG_4, "i=%d\n", i);
DEBUG(TAG_2, "p=%c\n", p);
return 0;
}
Right now I need only one argument passed. It appears the macro works as
expected, or I have not spotted bugs yet.
Is there anything wrong with this simple implementation (especially bit
operations)? Any advices are welcome.