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.


If you enjoyed this post, make sure you subscribe to my RSS feed!

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

Related posts:

  1. Renaming Files In Linux
  2. Fetch Links From Twitter Into Your RSS Reader
  3. Source Code of Steve Balmer Leaked
  4. Google Reader Useful “Send To” Services

Tags: , ,

Saturday, November 22nd, 2008 Programming

5 Comments to Using Macros to Print Debug Messages in C

  • sami says:

    مشكور على المعلومات القيمة يا ابو البلد

  • Amir Watad says:

    أهلاً وسهلاً. تعال كل يوم :)

  • wdef says:

    Handy macro – just what I was looking for.
    Thanks

  • Sonixant says:

    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!

  • Amir Watad says:

    Thank you @Sonixant :)

  • Leave a Reply

    my email
    Already a member?
    Login
    Login using Facebook:
    Last visitors
    my photo
    Hi,
    My name is Amir Watad. I have a BSc. in biomedical engineering from The Biomedical Engineering school , Technion , Israel, and am currently studying for a BSc. in electrical engineering at The Electrical Engineering school , Technion , Israel.
    I work at the verification dept. in Mellanox Technologies Ltd.
    I love Linux, the Command Line and the OpenSource Community.
    I used to write Poems (Arabic) when I was able to find time for this.
    November 2008
    S M T W T F S
    « Oct   Dec »
     1
    2345678
    9101112131415
    16171819202122
    23242526272829
    30  
    Firefox Logo Crystal
    SEO Powered by Platinum SEO from Techblissonline

    Twitter links powered by Tweet This v1.6.1, a WordPress plugin for Twitter.