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

后端 未结 7 788
走了就别回头了
走了就别回头了 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:43

    In GCC you can use the __PRETTY_FUNCTION__ macro.
    Microsoft also have an equivalent __func__ macro although I don't have that available to try.

    e.g. to use __PRETTY_FUNCTION__ putting something like this at the beginning of your functions and you'll get a complete trace

    void foo(char* bar){
      cout << __PRETTY_FUNCTION__ << std::endl
    }
    

    which will output

    void foo(char* bar)
    

    You also have the __FILE__ and __LINE__ macros available under all standard c/c++ compilers if you want to output even more information.

    In practice I have a special debugging class which I use instead of cout. By defining appropriate environment variables I can get a full program trace. You could do something similar. These macros are incredibly handy and it's really great to be able to turn on selective debugging like this in the field.

    EDIT: apparently __func__ is part of the standard? didn't know that. Unfortunately, it only gives the function name and not the parameters as well. I do like gcc's __PRETTY_FUNC__ but it's not portable to other compilers.

    GCC also supports __FUNCTION__.

提交回复
热议问题