These articles are written by Codalogic empowerees as a way of sharing knowledge with the programming community. They do not necessarily reflect the opinions of Codalogic.

GCC's __FUNCTION__ definitions

By: Pete, September 2020

If you play around with exploring the order in which functions are called in C++ you might have a lot of code that looks like std::cout << "in foo()";, std::cout << "in bar();.

If so, GCC's and Clang's __FUNCTION__ and __PRETTY_FUNCTION__ definitions may save you some effort and possibly some errors.

They are similar to the standard __FILE__ and __LINE__ definitions but in this case they print the name of the function in which they are used.

__FUNCTION__ simply displays the name of the function (e.g. func), whereas in C++ __PRETTY_FUNCTION__ includes the type information with the name (e.g. void func(const std::string&)).

In C, __PRETTY_FUNCTION__ displays the same as __FUNCTION__, presumably because C doesn't do name mangling.

Here's some example code (available here: https://godbolt.org/z/7dr5Ef6ss):

#include <iostream>

int func(int)
{
    std::cout << "__FUNCTION__ = " << __FUNCTION__ << "\n";
    std::cout << "__PRETTY_FUNCTION__ = " << __PRETTY_FUNCTION__ << "\n\n";
    return 0;
}

void func( const std::string & s )
{
    std::cout << "__FUNCTION__ = " << __FUNCTION__ << "\n";
    std::cout << "__PRETTY_FUNCTION__ = " << __PRETTY_FUNCTION__ << "\n\n";
}

struct A
{
    A()
    {
        std::cout << "__FUNCTION__ = " << __FUNCTION__ << "\n";
        std::cout << "__PRETTY_FUNCTION__ = " << __PRETTY_FUNCTION__ << "\n\n";
    }
    void who_am_i( void )
    {
        std::cout << "__FUNCTION__ = " << __FUNCTION__ << "\n";
        std::cout << "__PRETTY_FUNCTION__ = " << __PRETTY_FUNCTION__ << "\n\n";
    }
    ~A()
    {
        std::cout << "__FUNCTION__ = " << __FUNCTION__ << "\n";
        std::cout << "__PRETTY_FUNCTION__ = " << __PRETTY_FUNCTION__ << "\n\n";
    }
};

int main()
{

    func(0);
    func("");
    A a;
    a.who_am_i();
    std::cout << "__FUNCTION__ = " << __FUNCTION__ << "\n";
    std::cout << "__PRETTY_FUNCTION__ = " << __PRETTY_FUNCTION__ << "\n\n";
}

This outputs:

__FUNCTION__ = func
__PRETTY_FUNCTION__ = int func(int)

__FUNCTION__ = func
__PRETTY_FUNCTION__ = void func(const std::string&)

__FUNCTION__ = A
__PRETTY_FUNCTION__ = A::A()

__FUNCTION__ = who_am_i
__PRETTY_FUNCTION__ = void A::who_am_i()

__FUNCTION__ = main
__PRETTY_FUNCTION__ = int main()

__FUNCTION__ = ~A
__PRETTY_FUNCTION__ = A::~A()

I wish I had discovered this earlier!!!

Keywords