Code Yarns โ€๐Ÿ‘จโ€๐Ÿ’ป
Tech Blog โ– Personal Blog

How to get function name in C++

๐Ÿ“… 2018-Aug-22 โฌฉ โœ๏ธ Ashwin Nanjappa โฌฉ ๐Ÿท๏ธ function name, gcc, visual c++ โฌฉ ๐Ÿ“š Archive

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

There are many ways to obtain the function name in C++:

int A::foobar(const std::vector<float>& fvec, bool isDragon)
{
    std::cout << __func__ << std::endl;
    // Output: foobar
}

This is the only constant related to the function name that is defined in the C and C++ standards. The C++11 standard ยง8.4 describes this constant:

The function-local predefined variable __func__ is defined as if a definition of the form static const char __func__[] = "function-name "; had been provided, where function-name is an implementation-defined string.

Though the standards provide compilers the freedom to store whatever function details they want in this string, all the compilers that I have tried store only the function name in this string.

int A::foobar(const std::vector<float>& fvec, bool isDragon)
{
    std::cout << __func__ << std::endl;
    // Output: int A::foobar(const std::vector<float>&, bool)
}
#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]
#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: