Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

string - C++, get the name of the function

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...