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

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

    The C++ preprocessor macro __FUNCTION__ gives the name of the function.

    Note that if you use this, it's not really getting the filename, line number, or function name at runtime. Macros are expanded by the preprocessor, and compiled in.

    The __FUNCTION__ macro, like __LINE__, and __FILE__, is part of the language standard, and is portable.

    Example program:

    #include 
    #using namespace std;
    
    void function1()
    {
            cout << "my function name is: " << __FUNCTION__ << "\n";
    }
    int main()
    {
            cout << "my function name is: " << __FUNCTION__ << "\n";
            function1();
            return 0;
    }
    

    output:

    my function name is: main
    my function name is: function1
    

提交回复
热议问题