Sunday, February 22, 2009

[C/C++] Error tracing using __FILE__ and __LINE__

You might have seen the preprocessor directives __FILE__ and __LINE__. I shall explain how to use the same for error reporting in your application.
__FILE__ This macro holds the file name of the current execution context.
__LINE__ This macro holds the line number of the current source file's execution context.
With these macros you can make your error reporting more effective by specifying the file name and line number where error was occurred. This will help to troubleshoot the issue more effectively and easily. Following is a utility function which you can use to log error message to debug viewer.
// For converting integer line number to string
#define STR(X) #X
#define MAKE_STR(X) STR(X)

// For holding the file name & line number of error context
#define FILE_INFO __FILE__ ":" MAKE_STR( __LINE__ )

// Log the error message with file name and line no to debugview
void TraceError( const char* pcErrorLoc, const char* pcErrorMsg )
{
char szErrorMsg[MAX_PATH];
// Format msg to "Error at <filepath>:<line> - <message>"
sprintf( szErrorMsg, "Error at %s - %s", pcErrorLoc, pcErrorMsg );
OutputDebugString( szErrorMsg );
}
You can call the above utility function as shown below, if some error occur. Use the Debug Viewer for viewing the output.
// Call the function if error occured
TraceError( FILE_INFO, "Invalid input from the user" );

No comments: