Exercise 3-31 (Conditional debugging)
Chapter_3 Exercise_3-30 StringizingExpressions | Assert Exercise_3-32 |
Exercise 3-31 TCP1, p. 230
Exercise 3-31. Modify StringizingExpressions.cpp (see ch3-StringizingExpressions) so that P(A) is conditionally #ifdefed to allow the debugging code to be automatically stripped out by setting a command-line flag. You will need to consult your compiler’s documentation to see how to define and undefine preprocessor values on the compiler command line.
CONTENTS: cond_debug.c CondDebug.cpp
cond_debug.c download
#include <stdio.h> // for printf()
// Conditional debugging:
#ifdef debug
#define P(A) printf("%s: %d\n", #A, A) // no semicolon here
#else
#define P(A) // nothing
#endif
int main()
{
int a = 1, b = 2, c = 3;
P(a); P(b); P(c); // semicolons
P(a + b); // here
P((c - a)/b);
return 0;
}
/*
gcc cond_debug.c -o cond_debug
./cond_debug
gcc cond_debug.c -o cond_debug -D debug // define
./cond_debug
a: 1
b: 2
c: 3
a + b: 3
(c - a)/b: 1
gcc cond_debug.c -o cond_debug
./cond_debug
gcc cond_debug.c -o cond_debug -D debug=0
./cond_debug
a: 1
b: 2
c: 3
a + b: 3
(c - a)/b: 1
gcc cond_debug.c -o cond_debug -U debug // undef
./cond_debug
gcc cond_debug.c -o cond_debug -D debug=1
./cond_debug
a: 1
b: 2
c: 3
a + b: 3
(c - a)/b: 1
*/
Note: See Preprocessor_Options on GCC_online_documentation and Define_macro on SEGGER_Reference_Manual.
CondDebug.cpp download
#include <iostream>
using std::cout;
using std::endl;
// Conditional debugging:
#ifdef debug
#define P(A) cout << #A << ": " << (A) << endl // no semicolon here
#else
#define P(A) // nothing
#endif
int main()
{
int a = 1, b = 2, c = 3;
P(a); P(b); P(c); // semicolons
P(a + b); // here
P((c - a)/b);
return 0;
}
/*
g++ CondDebug.cpp -o CondDebug
./CondDebug
g++ CondDebug.cpp -o CondDebug -D debug // define
./CondDebug
a: 1
b: 2
c: 3
a + b: 3
(c - a)/b: 1
g++ CondDebug.cpp -o CondDebug
./CondDebug
g++ CondDebug.cpp -o CondDebug -D debug=0
./CondDebug
a: 1
b: 2
c: 3
a + b: 3
(c - a)/b: 1
g++ CondDebug.cpp -o CondDebug -U debug // undef
./CondDebug
g++ CondDebug.cpp -o CondDebug -D debug=1
./CondDebug
a: 1
b: 2
c: 3
a + b: 3
(c - a)/b: 1
*/
Chapter_3 Exercise_3-30 StringizingExpressions | BACK_TO_TOP | Assert Exercise_3-32 |
Comments
Post a Comment