首页 > 解决方案 > 如何在宏定义中连接 __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。

标签: c++cgccc-preprocessor

解决方案


给出编译错误 [...] 任何人都知道原因

__func__是一个变量:

static const char __func__[] = "function-name";

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

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


推荐阅读