Skip to content

Instantly share code, notes, and snippets.

@colematt
Last active September 24, 2017 23:37
Show Gist options
  • Save colematt/9b16cfd27918b347d8465f1b492a54f9 to your computer and use it in GitHub Desktop.
Save colematt/9b16cfd27918b347d8465f1b492a54f9 to your computer and use it in GitHub Desktop.
Using Preprocessor Directives for Troubleshooting

Using Preprocessor Directives for Troubleshooting

Suppose you have a bit of code you only want to run during your debugging. You don't want it to run in production mode (i.e. after you submit it for grading). A great example is diagnostic output that you print during troubleshooting. How can you do that without remembering to comment out all that debugging code manually? What if you forget?!

First, set up the preprocessor variable.

#define DEBUG 1

Next, use it to fence off the debugging actions.

#if DEBUG
  \\ Do this stuff
#endif

You can also get advanced and do one thing if set, do another thing if not set.

#if DEBUG
  \\ Do this stuff if DEBUG is set
#else
  \\ Do this stuff if DEBUG isn't set
#endif

Don't forget to turn DEBUG off before you submit! Go to the original #define line and change the value to zero.

#define DEBUG 0

This gist contains a simple program (main.c) that demonstrates this, along with a Makefile to build it. Run it like this:

$ ./main first second third last!

Try setting the DEBUG variable to see the other type of output. What changed?

Now you know how to set up conditional print statements that you can enable and disable as a group.

#include <stdio.h>
#include <string.h>
//Change this to 1 to enable the debugging output!
#define DEBUG 0
// This program iterates across the arguments
// and prints the length of each.
// If DEBUG is set, it also prints the argument itself
int main(int argc, char const *argv[]) {
#if DEBUG
puts("DEBUG is set!");
#endif
for (size_t i = 1; i < argc; i++) {
#if DEBUG
printf("len argv[%lu] (%s): %lu\n", i, argv[i], strlen(argv[i]));
#else
printf("len argv[%lu]: %lu\n", i, strlen(argv[i]));
#endif
}
return 0;
}
CFLAGS:= -g -Wall -std=c99
LDFLAGS:= -lc
all: main
main: main.c
$(CC) $(CFLAGS) $^ -o $@
.PHONY: clean
clean:
rm -fv main
@RichardLee0211
Copy link

skillful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment