c++ - 如何在宏定义中连接 __func__ 和 __LINE__
问题描述
我想定义一个宏来连接__func__
(或__FUNCTION__
)__LINE__
:
以下工作正常:
// macro_test.cc
#include <iostream>
#define STR2(X) #X
#define STR(X) STR2(X)
#define FILE_LOCATION __FILE__ ":" STR(__LINE__) " "
int main() {
std::cout << FILE_LOCATION << "is <file_name>:<line_number>" << std::endl;
return 0;
}
这是输出
$ ./a.out
macro_test.cc:8 is <file_name>:<line_number>
但是,以下给出了编译错误(我只是替换 __FILE__
为__func__
):
// macro_test.cc
#include <iostream>
#define STR2(X) #X
#define STR(X) STR2(X)
#define FUNC_LOCATION __func__ ":" STR(__LINE__) " "
int main() {
std::cout << FUNC_LOCATION << "is <function_name>:<line_number>" << std::endl;
return 0;
}
~$ gcc macro_test.cc
macro_test.cc: In function ‘int main()’:
macro_test.cc:5:32: error: expected ‘;’ before string constant
#define FUNC_LOCATION __func__ ":" STR(__LINE__) " "
^
macro_test.cc:8:16: note: in expansion of macro ‘FUNC_LOCATION’
std::cout << FUNC_LOCATION << "is <function_name>:<line_number>" << std::endl;
有谁知道这个的原因,我怎么能做到这一点?
我在 Linux(Ubuntu 18.04)上使用 gcc 5.4.0。
解决方案
给出编译错误 [...] 任何人都知道原因
__func__
是一个变量:
static const char __func__[] = "function-name";
它不是(字符串)文字(例如__FILE__
“扩展”。)
(文档在这里:https ://gcc.gnu.org/onlinedocs/gcc/Function-Names.html )
推荐阅读
- docker - 如何测量免费帐户用户的 Docker Hub 镜像拉取(参考 Docker Hub 从 2020 年 11 月 1 日起的新政策)?
- r - 每个 x 变量并排绘制箱线图
- mqtt - 主题名称中的 mqtt 时间戳:反模式?
- python - 使用 gitpython 从远程存储库添加 git 子模块
- android-studio - HMS Toolkit Android Studio 初始化失败
- excel - 如何在Excel中制作动态依赖下拉列表
- ios - 使用 iBeacon 时在 iOS 中最小化 Beacon Ranging 的电池消耗
- mysql - 取消嵌套节点数据库调用
- .net - 在 main 方法中区分应用程序
- f# - 在匹配的一个分支中使用异步方法