Macro / keyword which can be used to print out method name?

__FILE__ and __LINE__ are well known. There is a __func__ since C99.

#include <iostream>
struct Foo {
        void Do(){ std::cout << __func__ << std::endl; }
};

int main()
{
        std::cout << __func__ << std::endl;
        Foo foo; foo.Do();
        return 0;
}

will output

main
Do

Is there any macro / keyword that would output method name like Foo::Do?


Solution 1:

Boost has a special utility macro called BOOST_CURRENT_FUNCTION that hides the differences between the compiler implementations.

Following it's implementation we see that there are several macros depending on compiler:

  • __PRETTY_FUNCTION__ -- GCC, MetroWerks, Digital Mars, ICC, MinGW
  • __FUNCSIG__ -- MSVC
  • __FUNCTION__ -- Intel and IBM
  • __FUNC__ -- Borland
  • __func__ -- ANSI C99

Solution 2:

  • On GCC you can use __FUNCTION__ and __PRETTY_FUNCTION__.
  • On MSVC you can use __FUNCSIG__ and __FUNCTION__.

Solution 3:

There's no such macro in standard C++, and that includes the draft C++0x standard I looked at. It would complicate compilation, since parsing (necessary to determine what a function is) comes after preprocessing, and I suspect that's why there's nothing in the standard.

The __func__ you're using is nonstandard, although it apparently works on your compiler.