Runtime debugging flags
In some situations it is more convenient
to turn debugging flags on and off during program execution, especially by
setting them when the program starts up using the command line. Large programs
are tedious to recompile just to insert debugging code.
To turn debugging code on and off
dynamically, create bool flags:
//: C03:DynamicDebugFlags.cpp
#include <iostream>
#include <string>
using namespace std;
// Debug flags aren't necessarily global:
bool debug = false;
int main(int argc, char* argv[]) {
for(int i = 0; i < argc; i++)
if(string(argv[i]) == "--debug=on")
debug = true;
bool go = true;
while(go) {
if(debug) {
// Debugging code here
cout << "Debugger is now on!" << endl;
} else {
cout << "Debugger is now off." << endl;
}
cout << "Turn debugger [on/off/quit]: ";
string reply;
cin >> reply;
if(reply == "on") debug = true; // Turn it on
if(reply == "off") debug = false; // Off
if(reply == "quit") break; // Out of 'while'
}
} ///:~
This program continues to allow you to
turn the debugging flag on and off until you type “quit” to tell it
you want to exit. Notice it requires that full words are typed in, not just
letters (you can shorten it to letter if you wish). Also, a command-line
argument can optionally be used to turn debugging on at startup – this
argument can appear anyplace in the command line, since the startup code in
main( ) looks at all the arguments. The testing is quite simple
because of the expression:
string(argv[i])
This takes the argv[i] character
array and creates a string, which then can be easily compared to the
right-hand side of the ==. The program above searches for the entire
string --debug=on. You can also look for --debug= and then see
what’s after that, to provide more options. Volume 2 (available from
www.BruceEckel.com) devotes a chapter to the Standard C++ string
class.
Although a debugging flag is one of the
relatively few areas where it makes a lot of sense to use a global variable,
there’s nothing that says it must be that way. Notice that the variable is
in lower case letters to remind the reader it isn’t a preprocessor
flag.