Tuesday, February 26, 2008

Debugging C/C++ programs using simple printf

printf is a good tool for debugging c/c++ source code.
The following printf code can be used to print the values of function name file name and line number:

printf("\nFile is = %s , Function is = %s , Line number is = %d\n", __FILE__ , __FUNCTION__ , __LINE__);


There are two C preprocessor macros : __FUNCTION__ and __PRETTY_FUNCTION__ .
The two produce the same output in C, but the latter provides more information when it appears in a C++ module.

Example using the __PRETTY_FUNCTION__:

printf("\nFile is = %s , Function is = %s , Line number is = %d\n", __FILE__ , __PRETTY_FUNCTION__ , __LINE__);


yields either:
(in case of c)
File is foo.c ,Function is foo,Line Number is 230

"or"
(in case of c++)
File is foo.cpp ,Function is int c::foo,Line Number is 230

No comments: