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.
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.
(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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With