This post will discuss how to find the name of the calling function in C++.

1. Using Macros

In GCC, we can use the preprocessor macro __FUNCTION__ to find the undecorated name of the enclosing function. It gets expanded in the context of the caller at compile time by the preprocessor, and the function name will be inserted in the code. For example, the following code uses the __FUNCTION__ macro to display the function name information.

Download  Run Code

Output:

foo
main

 
The preprocessor macro __FUNCTION__ is available for both GCC and MSVC compilers. In GCC, __FUNCTION__ is another name for __func__, provided for backward compatibility with old versions of GCC. It can be used as follows:

Download  Run Code

Output:

foo
main

 
GCC also has the __PRETTY_FUNCTION__ macro, which is yet another name for __func__ but returns fully qualified name of the enclosing function. For example,

Download  Run Code

Output:

void foo()
int main()

2. Using __builtin_FUNCTION

All the above macros return the name of the enclosing function. To get the name of the caller function, consider using built-in function __builtin_FUNCTION() as a C++ default argument for the function.

Download  Run Code

Output:

Calling function: main

3. Using std::source_location

Starting with C++20, we can use std::source_location::function_name to return the name of the function represented by the std::source_location object. The source_location class is a better option over macros to get certain information about the source code, like file name, line number, function name, etc.

Download Code

Output:

main.cpp:13:int main()

4. Using boost

We can also use the boost C++ library to get the signature of the enclosing function with its bare name. The header <boost/current_function.hpp> defines a single macro, BOOST_CURRENT_FUNCTION which return the name of the current enclosing function.

Download Code

Output:

void foo()
int main()

References:

Function Names (Using the GNU Compiler Collection (GCC))

That’s all about finding the name of the calling function in C++.