General Programming - Debug

Introduction

When I'm coding, depending on the programming language, I usually like to sprinkle debugging statements into my code to see data, code decisions and general information while the program is executing.  Using the Arduino, I can use the Serial library to stream print statements to the Serial Monitor for example.

Option 1: In code #if

The first option is very simple.  At the top of your source file, you put in the following line when you want to turn debugging code on:

#define DEBUG

Then in your code, you can put lines like the following that will be compiled and executed when the DEBUG flag is present, but will not be included in your code when the #define is removed:

#ifdef DEBUG
  Serial.println("Debugging statement");
#endif

Option 2: Debug Macro

Another option is to create a header file with a debugging macro that will execute or remove the code as requested.  You still need to define DEBUG, but you also need a header file included that contains the following:

 


 

Debug.h

#ifndef DEBUG_H
#define DEBUG_H

#ifdef DEBUG
#define DebugCode( code_fragment ) { code_fragment }
#else
#define DebugCode( code_fragment )
#endif

#endif


 

Then, in your code you would use debugging code as follows:

DebugCode(
  Serial.print("display and ");
  Serial.println("debugging statements go here");

)

Later on in our development cycle, would could add more to the DebugCode macro to always display a variable for example.  We would do this like:

#define DebugCode( code_fragment ) { \
  Serial.print("x="); \
  Serial.println(x); \
  code_fragment }

Now whenever we perform our debug code during execution, we would always see the value of our 'x' variable.

Conclusion

Both options are equally good in my opinion.  My preference is the second option because it leaves itself open to more customization and has the added benefit of not having to type and see all the #ifndef DEBUG...#endif statements cluttering up my code.

I'm sure there are many schools of thought on the handling of debug code. Let me know your thoughts.

Maus