Using Macros to Print Debug Messages in C
I have to confess: It’s my first time using macros for debug, I used to just add printf-s when developing and remove them when the code is ready – Which is and ugly and very unprofessional in my opinion.
So, I decided to start caring about how my code looks, even in development stage. Here how I use macros for debug messages. (I needed the help of a friend to get this work).
first of all, define this:
1
2
3
4
5
6
7 #define DEBUG
#ifdef DEBUG
#define PRINT_DEBUG(format, args...) printf("\033[31m"format"\033[0m", ##args);
#else
#define PRINT_DEBUG(format, args...)
#endif
(The “strange” \033[31m characters tell the shell to print messages in Red, see my previous post about printing color in Linux)
Now, in your code, to print a debug message, just write something like this:
1 PRINT_DEBUG("This is a Debug Message: x+y = %d\n", x+y);
When you’re done developing, just remove the #define DEBUG from your code, and you’re done, no debug messages, and your program’s output is clean.
Related posts:
5 Comments to Using Macros to Print Debug Messages in C
Leave a Reply
About Me
Tags
My Twitter
Categories
- Algorithms
- Bash
- BlackBerry
- Collaboration
- Command Line
- Cool Tricks
- Easter Eggs
- Ebooks
- Firefox
- Hardware
- Humor
- Linux
- Linux Development
- Linux Kernel
- Networks
- Open Knowledge
- Other
- Productivity
- Programming
- Science
- Security
- Shell Scripts
- Short Posts
- Thoughts
- Tools
- Vim
- Web Development
- Websites
Popular Posts
Calendar
Archives
- March 2010 (1)
- January 2010 (1)
- December 2009 (2)
- September 2009 (13)
- July 2009 (1)
- June 2009 (6)
- May 2009 (4)
- March 2009 (18)
- February 2009 (10)
- January 2009 (10)
- December 2008 (7)
- November 2008 (8)
- October 2008 (1)
- August 2008 (1)
- July 2008 (1)
- June 2008 (2)

مشكور على المعلومات القيمة يا ابو البلد
أهلاً وسهلاً. تعال كل يوم
Handy macro – just what I was looking for.
Thanks
Instead of defining DEBUG from the code you can define it at compile time directly from gcc, e.g.:
$ gcc -DDEBUG …
you can even create a target rule for debugging in your makefile, just add the rule:
debug:
$(MAKE) DBGFLAGS=”-DDEBUG”
this way a simple:
$ make debug
makes the trick!
Thank you @Sonixant