How to get function name in C++

Being able to access and print the function name from any location inside a C++ function can be useful for investigating programs.

There are multiple function name strings depending on the compiler you are using:

  • __func__ is a constant that holds only the name of the function. It is part of the C and C++ standards. This is the only standards compliant constant.
int A::foobar(const std::vector<float>& fvec, bool isDragon)
{
    std::cout << __func__ << std::endl;
    // Output: foobar
}
  • __FUNCTION__ is a GCC and Visual CPP constant whose output is exactly the same as __func__.

  • __PRETTY_FUNCTION__ is a GCC constant that is more useful for C++, because it holds the entire function signature:

int A::foobar(const std::vector<float>& fvec, bool isDragon)
{
    std::cout << __func__ << std::endl;
    // Output: int A::foobar(const std::vector<float>&, bool)
}
  • __FUNCDNAME__ is a Visual CPP constant holding the mangled function name.

  • __FUNCSIG__ is a Visual CPP constant holding the function signature with information about input, output and template types.

  • Example program and its output with GCC compiler:

#include <iostream>

template <typename T>
void foo(T i)
{
    std::cout << __func__ << std::endl;
    std::cout << __FUNCTION__ << std::endl;
    std::cout << __PRETTY_FUNCTION__ << std::endl << std::endl;
}

int main()
{
    foo<int>(10);
    foo<float>(3.14);
    return 0;
}

// Output:
// foo
// foo
// void foo(T) [with T = int]
// 
// foo
// foo
// void foo(T) [with T = float]
  • Example program and its output with Visual CPP compiler:
#include <iostream>

template <typename T>
void foo(T i)
{
    std::cout << __func__ << std::endl;
    std::cout << __FUNCTION__ << std::endl;
    std::cout << __FUNCDNAME__ << std::endl;
    std::cout << __FUNCSIG__ << std::endl << std::endl;
}

int main()
{
    foo<int>(10);
    foo<float>(3.14);
    return 0;
}

// Output:
// foo
// foo
// ??$foo@H@@YAXH@Z
// void __cdecl foo<int>(int)
// 
// foo
// foo
// ??$foo@M@@YAXM@Z
// void __cdecl foo<float>(float)

References:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.