【发布时间】:2020-08-16 01:07:17
【问题描述】:
我想定义一个宏来连接__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。
【问题讨论】:
-
STR(__func__)? -
@bolov 和
STR(__func__)输出为:__func__:8 is <function_name>:<line_number> -
#define FUNC_LOCATION [](auto fn, auto ln) { std::stringstream ss; ss << fn << ":" << ln << " "; return ss.str(); }(__func__, __LINE__) -
@Eljay 在回答中怎么说?另一个答案说为什么 OP 提案不起作用但没有回答 OP 问题“如何做”
标签: c++ c gcc c-preprocessor