C++宏获取完整的函数路径和声明

C++ macro to get full function path and declaration

本文关键字:函数 路径 声明 获取 C++      更新时间:2023-10-16

我想通过宏或一些编译器魔术在代码中获得完整的函数路径和声明。我有这个代码(点击这里运行):

#include <iostream>
namespace NS {
    struct Foo {
        static int sum(int a, int b) {
            std::cout << "This is from " << __FILE__ << ":" << __LINE__ << " @ " <<     __func__ << std::endl;
            return a+b;
        }
        static int sum(int a, int b, int c) {
            std::cout << "This is from " << __FILE__ << ":" << __LINE__ << " @ " <<     __func__ << std::endl;
            return a+b+c;
        }
   };
}
int main() {
    NS::Foo::sum(1,2);
    NS::Foo::sum(1,2, 3);
}

我得到了输出:

This is from /some/where/main.cpp:7 @ sum
This is from /some/where/main.cpp:12 @ sum

我的问题是:

  • 如何获取调用的sum函数的完整路径?(NS::Foo::sum)
  • 如何获得带有参数类型的完整函数声明?(sum(int, int)sum(int, int, int)

我对主流编译器感兴趣:Clang, GCC, Microsoft C++ compiler

GCC的应答。

检出__PRETTY_FUNCTION__宏。我在<assert.h>中的assert宏的定义中找到了它。也许其他编译器和libc实现也是如此。

对于Microsoft Visual Studio编译器,__FUNCSIG__可以为您提供很多关于该函数的信息。

__FUNCSIG__将为您提供全功能签名
__FUNCDNAME__给出了magned的名称
__FUNCTION__仅用于函数名称。

如果你不想把自己局限于一个编译器,也不想自己编写一个预处理器ifdef链,boost已经定义了一个宏BOOST_CURRENT_FUNCTION,它被定义为在所用编译器上定义的全函数签名宏。gcc中的__PRETTY_FUNCTION__和其他支持它的编译器,支持它的__FUNCSIG__(msvc),也支持一些较少使用的编译器,并返回到C标准定义的__func__(或者静态占位符,如果不支持的话)。