tracing_example.cpp

This code exemplifies how to insert trace statements to follow the flow of program execution. When compiler under gcc 3.3 and run, the following program will output the following trace:
00001         trace[1]: Entering int main()
00002         trace[2]: Entering int foo(int)
00003         trace[3]: Entering int Foo::bar(int)
00004         trace[3]: i = 21
00005         trace[3]: At line 16 in tracing_example.cpp
00006         trace[3]: Wrong answer
00007         trace[3]: i = 42
00008         trace[3]: Exiting int Foo::bar(int)
00009         trace[3]: Entering int Foo::bar(int)
00010         trace[3]: i = 42
00011         trace[3]: At line 13 in tracing_example.cpp
00012         trace[3]: Right answer, but no question
00013         trace[3]: i = 42
00014         trace[3]: Exiting int Foo::bar(int)
00015         trace[2]: Exiting int foo(int)
00016         trace[1]: Exiting int main()
Of course, a word of warning must be added: adding so much tracing to your code might degrade its readability, at least until we devise an Emacs macro to hide trace statements with a couple of keystrokes.

00001 
00002 #include <ql/quantlib.hpp>
00003 
00004 using namespace QuantLib;
00005 
00006 namespace Foo {
00007 
00008     int bar(int i) {
00009         QL_TRACE_ENTER_FUNCTION;
00010         QL_TRACE_VARIABLE(i);
00011 
00012         if (i == 42) {
00013             QL_TRACE_LOCATION;
00014             QL_TRACE("Right answer, but no question");
00015         } else {
00016             QL_TRACE_LOCATION;
00017             QL_TRACE("Wrong answer");
00018             i *= 2;
00019         }
00020 
00021         QL_TRACE_VARIABLE(i);
00022         QL_TRACE_EXIT_FUNCTION;
00023         return i;
00024     }
00025 
00026 }
00027 
00028 int foo(int i) {
00029     using namespace Foo;
00030     QL_TRACE_ENTER_FUNCTION;
00031 
00032     int j = bar(i);
00033     int k = bar(j);
00034 
00035     QL_TRACE_EXIT_FUNCTION;
00036     return k;
00037 }
00038 
00039 int main() {
00040 
00041     QL_TRACE_ENABLE;
00042 
00043     QL_TRACE_ENTER_FUNCTION;
00044 
00045     int i = foo(21);
00046 
00047     QL_TRACE_EXIT_FUNCTION;
00048     return 0;
00049 }
00050