如何在宏定义中连接 __func__ 和 __LINE__

Cur*_*ous 2 c c++ gcc c-preprocessor

我想定义一个宏来连接__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;
}
Run Code Online (Sandbox Code Playgroud)

这是输出

$ ./a.out 
macro_test.cc:8 is <file_name>:<line_number>
Run Code Online (Sandbox Code Playgroud)

但是下面给出了一个编译错误(我只是用 替换 __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;
Run Code Online (Sandbox Code Playgroud)

有谁知道这是什么原因,我怎样才能做到这一点?

我在 Linux (Ubuntu 18.04) 上使用 gcc 5.4.0。

alk*_*alk 5

给出一个编译错误 [...] 任何人都知道这是什么原因

__func__ 是一个变量:

static const char __func__[] = "function-name";
Run Code Online (Sandbox Code Playgroud)

不是(字符串)文字(例如__FILE__“扩展”。)

(文档在这里:https : //gcc.gnu.org/onlinedocs/gcc/Function-Names.html