gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:44:51 25 4
gpt4 key购买 nike

我想定义一个宏来连接__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。

最佳答案

gives a compilation error [...] anyone know the reason for this

__func__ 是一个变量:

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

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

(文档位于: https://gcc.gnu.org/onlinedocs/gcc/Function-Names.html )

关于c++ - 如何在宏定义中连接 __func__ 和 __LINE__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61544241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com