This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  A Better FAILED Macro
  Submitted by



For the past month I have been working on a new 3D engine. I've been constantly trying to find better ways to debug my code and find errors faster. Along with asserts and VC's memory allocation tracker, I also use a little macro redefinition to track down function failures. I'm sure many of you use the Windows macro FAILED(). The problem I was having was not knowing which function actually failed. I came up with this to help me out.

//in Debug.h
HRESULT OpenDebugFile(TCHAR *szFileName);

void CloseDebugFile();

#ifdef _DEBUG HRESULT FailureTest(HRESULT,TCHAR*,INT);

#ifdef FAILED #undef FAILED #endif #define FAILED(result) FailureTest(result, _T(__FILE__), _T(__LINE__)); #endif //********************************************************* //in Debug.cpp ofstream g_DbgOut;

HRESULT OpenDebugFile( TCHAR* szFileName ) { g_DbgOut.open( szFileName ); if( g_DbgOut.good() ) return S_OK;

return E_FAIL; }

void CloseDebugFile() { if( g_DbgOut.good() ) g_DbgOut.close(); }

HRESULT FailureTest( HRESULT hr, TCHAR* szFile, INT iLine ) { BOOL bFailed = ( hr < 0 );

assert(g_DbgOut.good());

if( bFailed ) g_DbgOut << "Function Failure: " << "File: " << szFile << ", " << "Line:" << iLine << endl;

return bFailed; } //***************************************************** //in use void main() { OpenDebugFile( _T("Debug.txt") ); //should check for failure HRESULT hr = Func(); if( FAILED( hr ) ) goto Cleanup;

/****Other code****/

Cleanup: CloseDebugFile();

}

//Output Function Failure: File: /*Path with file name*/, Line: 4



You can then go back to your code and determine the exact function that failed. Dumping this info to the debug window is also possible. The other nice thing is that this code slips in nicely to any code using the FAILED macro without any changes to the existing code base. And in a release build, you end up using the original definition of FAILED. One problem that comes up is if your program crashes before closing the file, you will obviously will have an empty file. If anyone has a good, eligent solution to this problem, please let me know.

Aaron


The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.