How to find the name of the current function at runtime?

后端 未结 7 855
走了就别回头了
走了就别回头了 2021-01-31 15:17

After years of using the big ugly MFC ASSERT macro, I have finally decided to ditch it and create the ultimate ASSERT macro.

I am fine with getting the file and line num

7条回答
  •  终归单人心
    2021-01-31 15:38

    You can use the __FUNCTION__ macro which at compile time will be expanded to the name of the function.

    Here's an example of how to use it in an assert macro.

    #define ASSERT(cond) \
        do { if (!(cond)) \
        MessageBoxFunction("Failed: %s in Function %s", #cond, __FUNCTION__);\
        } while(0)
    
    void MessageBoxFunction(const char* const msg,  ...)
    {
        char szAssertMsg[2048];
    
        // format args
        va_list vargs;
        va_start(vargs, msg);
        vsprintf(szAssertMsg, msg, vargs);
        va_end(vargs);
    
        ::MessageBoxA(NULL, szAssertMsg, "Failed Assertion", MB_ICONERROR | MB_OK);
    }
    

提交回复
热议问题