home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 1 / 1268 < prev    next >
Encoding:
Internet Message Format  |  1990-12-28  |  2.0 KB

  1. From: rosenber@ra.abo.fi (Robin Rosenberg INF)
  2. Newsgroups: comp.lang.c,comp.unix.wizards,alt.sources,comp.sources.d,misc.misc
  3. Subject: Re: #define DEBUG... (using printf for debugging)
  4. Message-ID: <ROSENBER.90May4184448@ra.abo.fi>
  5. Date: 4 May 90 15:44:48 GMT
  6.  
  7.  
  8. >I want to have a DEBUG flag which controls whether diagnostic printfs 
  9. >are executed or not.                                                  
  10.  
  11. I have used the following macros for a while now and they work fine.
  12.  
  13. /* tdebug.h  -- tracing & debugging macros
  14.  *
  15.  */
  16. #if TDEBUG
  17.     #define T(s)        {dprintf("\033[33m(\033[0m%s\033[0m",#s);{s} dprintf("\033[33m)\033[0m\r\n");}
  18.     #define D(s)        s
  19.     #define P(a)        dprintf a
  20.     #define V(n,x)      {if (debuglevel>=n) dprintf("%s\r\n",x);}
  21. #else
  22.     #define T(s)        {s}     /* ! trace execution of statements */
  23.     #define D(s)        ;       /* ! execute only when debugging */
  24.     #define P(a)                /* ! printf when debugging */
  25.     #define V1(n,x)     {}
  26. #endif TDEBUG
  27. /* eof */
  28.  
  29. dprintf has the same synopsis as printf, however if may be some other
  30. function. Which function it is is defined at link time. Usually dprintf asks
  31. another process to print the debugging info for me. If your system does not
  32. allow you to define symbols at link time, replace dprintf with the funtion
  33. you want in tdebug.h
  34.  
  35. Note however that the T() macro doesn't work in all cases. Most notably it
  36. may have to be written differently for other compilers and may not work if
  37. the statement beging traced contains double quotes.
  38.  
  39. Also, the ANSI escape sequences used in the T() macro is to help matching
  40. parentheses in the trace output.
  41.  
  42. Here is a sample (not useful) program using these macros
  43.  
  44. #define TDEBUG 1    /* or 0 if debugging is not wanted */
  45. #include "tdebug.h"
  46.  
  47. int debuglevel;
  48.  
  49. main(int argc,char **argv)
  50. {
  51.     debuglevel = atoi(argv[1]);
  52.     P(("This is a demo. Prog =%s\n",argv[0]));
  53.     T(subroutine(argc,argv);)
  54.     V(1,"I will now fall off the e");
  55. }
  56.  
  57. You may use or modify these macros as you like according to your needs.
  58. Enjoy!
  59.  
  60. -----------
  61. Robin Rosenberg
  62.