C++,获取函数的名称

Max*_*rai 15 c++ string function

在C++中,有没有办法从它的指针中获取函数签名/名称?

void test(float data) {}
cout << typeid(&test).name();
Run Code Online (Sandbox Code Playgroud)

我想使用这些数据进行日志记录.

Eri*_*ski 21

C++,通过指针获取调用函数的名称:

选项1:滚动您自己的功能名称记录器

如果要将"指向函数的指针"解析为"函数名",则需要创建自己的所有可用函数的查找表,然后将指针地址与查找表中的键进行比较,并返回名称.

此处描述的实现:https: //stackoverflow.com/a/8752173/445131

选项2:使用 __func__

GCC提供了这个魔术变量,它将当前函数的名称保存为字符串.它是C99标准的一部分:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

the name of this function is: main
the name of this function is: foobar_function
Run Code Online (Sandbox Code Playgroud)

笔记:

__FUNCTION__是另一个名字__func__.较旧版本的GCC仅识别此名称.但是,它没有标准化.如果需要最大可移植性,我们建议您使用__func__,但为预处理器提供回退定义,以定义它是否未定义:

 #if __STDC_VERSION__ < 199901L
 # if __GNUC__ >= 2
 #  define __func__ __FUNCTION__
 # else
 #  define __func__ "<unknown>"
 # endif
 #endif
Run Code Online (Sandbox Code Playgroud)

资料来源:http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html


Jac*_*sky 17

如果您只想记录当前函数名,那么大多数编译器都有__FUNCTION__宏,它将在编译时为您提供当前函数名.

您还可以查找堆栈遍历技术(这是Windows的示例),它可以在运行时为您提供有关当前调用堆栈和函数名称的更多信息.

  • `__func__`是标准的,它必须在那里; `__FUNCTION__`可能是一些非标准的.`__PRETTY_FUNCTION__`也值得一提. (8认同)
  • 不是`__func__`吗?http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html 指出这在技术上不是宏。 (3认同)