From: utzoo!decvax!harpo!floyd!vax135!ariel!houti!hogpc!houxm!houxz!hocda!spanky!burl!duke!mcnc!unc!tim Newsgroups: net.lang.c Title: C DEBUG macro (stop me if you've heard this) Article-I.D.: unc.5084 Posted: Thu Apr 28 22:47:37 1983 Received: Sat Apr 30 06:30:22 1983 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