tim (04/29/83)
I thought everyone knew this trick, but I've found out I'm wrong. This is submitted for the benefit of those who haven't seen it before, and others will kindly refrain from flaming. Place the following piece of code at the beginning of a C source file, or put it in a file and "# include" the file at the top of your program. # ifdef DEBUG # undef DEBUG # define DEBUG printf # else # define DEBUG(arg) # endif Throughout your program, you should place lines of the form DEBUG(msg,arg1,...) ; The file is now capable of being compiled in two different ways. Say that the file is "prog.c" for these examples. (1) If you compile with the flag "-DDEBUG" on the command line, e.g., % cc -DDEBUG prog.c then the DEBUG statements will turn into printf's, and print your debugging information on the standard output when the program runs. (2) If you compile without the "-DDEBUG" flag, then the DEBUG statements will become null statements, for which the compiler generates no code. Thus you can insert debugging probes all through any C functions, yet never have to remove them, or compile in a special way, for the finished version of your program. The only overhead (typing the "-DDEBUG" flag and macroexpanding the DEBUG's) is negligible, and there is no extra cost at execution time. Of course, there are other ways of using this trick, but I decided to submit a complete and usable example, and let people work out their own variations if they wished. Tim Maroney
tim (04/29/83)
There was an error in my previous article. Sorry. The DEBUG statements can only be of the form DEBUG(msg); . The reason is that the C macro processor can only cope with fixed-length argument lists, for some silly reason. If you want to have other arguments, then you will have to have each argument list be the same size. Supplying NULL arguments as padding to your DEBUGs should work, but may not on your system (due to the fact that printf behavior when given a weird argument list is undefined). The only safe way is to use only single-argument printf's, or to have all your printf format strings accept the same number of arguments. Again, sorry for any inconvenience caused. The DEBUG macro I gave is still quite useful, despite its limitations. Tim Maroney
ka (04/29/83)
To make a DEBUG macro which can handle arbitrary printf statements, say #define DEBUG(arglist) printf arglist and invoke with double parnethesis around the argument list, as in DEBUG(("x = %d\n", x)); Kenneth Almquist