| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • Browse and search Google Drive and Gmail attachments (plus Dropbox and Slack files) with a unified tool for working with your cloud files. Try Dokkio (from the makers of PBworks) for free. Now available on the web, Mac, Windows, and as a Chrome extension!

View
 

DebugMessages

Page history last edited by Kenneth Finnegan 12 years, 10 months ago

I use this trick a lot to see how many times a function is called or what section of code a segmentation fault came from.  The useful part about this trick is that once all the messages are in the code, them being compiled into the program is optional.

 

Code:

#ifdef DEBUG

#define ErR(a) fprintf(stderr, "%s\n", a)

#else

#define ErR(a) NULL

#endif

 

Usage:

// hello.c

main() {

     ErR("Beginning of main");

     printf("Hello World!\n");

     ErR("End of main");

}

 

Compile with:

cc -o hello hello.c -DDEBUG

The -D flag defines the symbol after it, so ErR gets replaced with fprintf only if DEBUG is defined, otherwise it disappears.

 


Extensions:

If the debug messages are going by too fast, you can add in a second clause for DEBUG_SLOW being defined to pause 1 seconds after each message

#if defined DEBUG

#define ErR(a) fprintf(stderr, "%s\n", a)

#elif defined DEBUG_SLOW

#define ErR(a) fprintf(stderr, "%s\n", a); sleep(1)

#else

#define ErR(a) NULL

#endif

 

If you want something more general than just printing messages, you can instead do:

#ifdef DEBUG

#define IF_DEBUG(a) (a)

#else

#define IF_DEBUG(a) NULL

#endif

 

For a very good outline on how to have the program also display which file and which line in the file the message was from, read this article.


Sources:

http://kennethfinnegan.blogspot.com/2008/03/debugging-messages-in-c.html

http://www.gnu.org/software/wget/

http://www.decompile.com/cpp/faq/file_and_line_error_string.htm

Comments (0)

You don't have permission to comment on this page.