Search code examples
c++visual-studiovisual-studio-2010directx-9

Can I Access a calling function's name programmatically?


I'm hoping to add a little functionality to a Log File system for a project I'm working on. For my LogError() calls, I would like to include the function the error occurred in. I'm wondering if there's a way that I can access the name of the function that called LogError() so I can programmatically access that information to add it to the log.

For example:

bool Engine::GraphicsManager::Initialize(const HWND i_hWindow_main)
{
    if ( !InitializeWindow( i_hWindow_main ) )
    {
        Engine::LogManager::Instance().LogError(L"GraphicsManager::Initialize - Unable to initialize graphics window");
        return false;
    }
    Engine::LogManager::Instance().LogMessage(L"Graphics window initialized successfully");

    /* SNIP */

    initialized = true;
    return true;
}

In the above example, I'd like LogError() to be able to determine that it was called from GraphicsManager::Initialize() and output (at least part of) that function's name instead of putting that in everywhere by hand.

EDIT: I should have mentioned that my LogError() function (and the other logging functions) are essentially wrappers for vfwprintf_s() so they can take variable length argument lists. While I like the "use a macro" suggestions, I'm not sure how to tackle that potential issue (which is likely another question).

Is this still reasonable/possible?

Thanks!


Solution

  • You could add an argument for the function name, and pass in the __FUNCTION__ macro: http://msdn.microsoft.com/en-us/library/b0084kay%28v=vs.80%29.aspx

    And you could also define a macro that will automatically replace ...log...() with ...log...(__FUNCTION__).