Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, get the name of the function

Tags:

In C++, is there a way to get the function signature/name from it's pointer like this?

void test(float data) {}
cout << typeid(&test).name();

I want to use this data for logging.

like image 519
Max Frai Avatar asked Jun 20 '10 10:06

Max Frai


People also ask

What is the caller in C?

Function Calling:It is called inside a program whenever it is required to call a function. It is only called by its name in the main() function of a program. We can pass the parameters to a function calling in the main() function.

What is __ function __ in C?

(C++11) The predefined identifier __func__ is implicitly defined as a string that contains the unqualified and unadorned name of the enclosing function. __func__ is mandated by the C++ standard and is not a Microsoft extension.


2 Answers

C++, get the name of the calling function via a pointer:

Option 1: roll your own function name recorder

If you want to resolve a "pointer to a function" to a "function name", you will need to create your own lookup table of all available functions, then compare your pointer address to the key in the lookup table, and return the name.

An implementation described here: https://stackoverflow.com/a/8752173/445131

Option 2: Use __func__

GCC provides this magic variable that holds the name of the current function, as a string. It is part of the C99 standard:

#include <iostream>
using namespace std;
void foobar_function(){
    cout << "the name of this function is: " << __func__ << endl;
}
int main(int argc, char** argv) {
    cout << "the name of this function is: " << __func__ << endl;
    foobar_function();
    return 0;
}

Output:

the name of this function is: main
the name of this function is: foobar_function

Notes:

__FUNCTION__ is another name for __func__. Older versions of GCC recognize only this name. However, it is not standardized. If maximum portability is required, we recommend you use __func__, but provide a fallback definition with the preprocessor, to define it if it is undefined:

 #if __STDC_VERSION__ < 199901L
 # if __GNUC__ >= 2
 #  define __func__ __FUNCTION__
 # else
 #  define __func__ "<unknown>"
 # endif
 #endif

Source: http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html

like image 58
Eric Leschinski Avatar answered Oct 22 '22 09:10

Eric Leschinski


If you just want to log the current function name, most of the compilers have __FUNCTION__ macro, which will give you the current function name at compile time.

You may also look for stack walking techniques (here is an example for Windows), which can provide you more information about the current call stack and function names at runtime.

like image 32
Jack Shainsky Avatar answered Oct 22 '22 09:10

Jack Shainsky