C++宏获取完整的函数路径和声明
C++ macro to get full function path and declaration
我想通过宏或一些编译器魔术在代码中获得完整的函数路径和声明。我有这个代码(点击这里运行):
#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__
(或者静态占位符,如果不支持的话)。
相关文章:
- 从函数角度看ID到文件路径的内部与外部映射
- C++:如何为多个重载函数保留通用代码路径?
- 函数路径追加上未解决的外部符号错误
- 在结构函数之间传递文件路径 C++ 编辑:修复LNK2019错误
- 使函数接受字符串变量内的路径
- 库路径绝对是正确的,可以创建所述库的实例,但在调用任何函数时"Undefined reference"
- C++'Undefined reference to'错误,尽管包含路径中的头文件中存在函数定义
- C++通过此函数的所有路径都将在宏中调用自身
- Cmake找到了通往OpenCV库的路径,但没有找到OpenCV函数Rodrigues
- c++ 函数向文件路径添加额外的"\"?
- MISRA-C++:2008[8-4-3]:返回函数中的所有出口路径
- 计算图中路径的递归函数的复杂性
- C++重命名函数不适用于绝对路径
- 实现用于查找路径的递归函数时出现问题
- 使用 Qt 进行单元测试:更改测试函数中使用的标准路径
- 如何编写递归函数来计算图形数据结构中的最短路径
- 一个单元如何测试C++序列的所有路径(单个或多个函数或类)
- C++宏获取完整的函数路径和声明
- POSIX 或 Linux API 函数,用于从路径获取文件扩展名
- 为什么使用 mkdir () 函数比使用 system ('mkdir 路径')快得多?