Computer Networks (CSC-364 2000S)


Debugging Messages in C

Many of you learned to program in systems that had no debugger. Hence, you debug by printing out messages. This is not a bad idea, but it is certainly less good than using a debugger. If you insist on printing error messages, at least do it in a way that lets you turn them off. Here's one possibility.

Step 1. The Header File

Create a file, debug.h, that you include in programs that you might debug. The file should look something like the following.

#ifndef _DEBUG_H_
#define _DEBUG_H_

#include <stdio.h>

/* Macros to help in debugging.  Compile your program with -DDEBUG
 * if you want debugging messages printed.  Don't use the -DDEBUG
 * if you don't want the messages printed.  Print your debugging 
 * messages with S_NOTE(string) and I_NOTE(string,int).  For example,
 *
 *   S_NOTE("Entered factorial");
 *   I_NOTE("N", N);
 *
 * Author: Sam Rebelsky
 * Verson: 1.0 of February 2000
 */
 
#ifdef DEBUG

#define S_NOTE(str) fprintf(stderr, "DEBUG: %s\n", str)
#define I_NOTE(i) fprintf(stderr, "DEBUG: %s is %d\n", i)

#else

#define S_NOTE(str)
#define I_NOTE(i)

#endif /* DEBUG */

#endif /* _DEBUG_H_ */

Step 2. Add Messages to Your Code

Whenever you want a simple string message printed, use

S_NOTE(message);

Whenever you want to print an integer variable, use

I_NOTE(variable_name,variable)

Step 3. Compile Appropriately

When you want debugging messages on, compile your program with -DDEBUG. When you don't want debugging messages on, compile your program without it. If you use make, it helps to define a CFLAGS variable.

CFLAGS=-DDEBUG
CC=gcc

History

Sunday, 13 February 2000


Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.

This page may be found at http://www.math.grin.edu/~rebelsky/Courses/CS364/2000S/Handouts/debugging.html

Source text last modified Mon Feb 14 07:48:26 2000.

This page generated on Mon Feb 14 07:56:14 2000 by Siteweaver. Validate this page's HTML.

Contact our webmaster at rebelsky@grinnell.edu