Wednesday 21 April 2010

Printing Debug information through Macros

This example shows probably one of the most useful case for using Macro's. Since Macro's are expanded before the code is compiled, debug information like filename and line number is available in the macro to be used.




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

#define PRINT_DEBUG_INFO \
cout<<__DATE__<<" "<<__TIME__<<": "<<__FUNCTION__<<", "<<__FILE__<<", "<<__LINE__<<endl;
//Note that __TIMESTAMP__ can be used instead of __DATE__ and __TIME__

void
func1(int* someNum)
{

if
(someNum)
{

//Perform normal operations here
int someVar=0;
}

else

{

//Abnormal scenario
PRINT_DEBUG_INFO;
}
}


void
func2(int *); //forward declaration of func2

int
main()
{

int
*x = NULL;
func1(x); //Creating exception scenario
func2(x); //Creating exception scenario

return
0;
}


void
func2(int* someNum)
{

try

{

//Normal case here
if(someNum)
*
someNum = 100;
else
throw
0;
}

catch
(...) //Abnormal case
{
PRINT_DEBUG_INFO;
}
}





The output is as follows:
Please note that in the above example, the __DATE__ and __TIME_ functions return the compilation date and time, not the current date and time. More details here.

To get the current execution date and time, see this example.

No comments:

Post a Comment