如何让__FILE __,__ func__和__LINE__宏在单行中工作?

问题描述 投票:0回答:2

C++ concatenating __FILE__ and __LINE__ macros?问题的接受答案适用于FILE和LINE,但我也想添加func宏。

#define S1(x) #x
#define S2(x) S1(x)
#define S3(x) x

#define LOCATION __FILE__ " : " S3(__func__) " : " S2(__LINE__)

这给出了错误

log.cpp|15 col 15 error| note: in definition of macro ‘S3’

也尝试过,

#define LOCATION __FILE__ " : " __func__ " : " S2(__LINE__)

给出错误

log.cpp|30 col 9 error| note: in expansion of macro ‘LOCATION’

我知道LINE是一个整数,因此需要#x,但func是一个char数组。我该如何工作?有帮助吗?

c++11 macros
2个回答
2
投票

正如cpplearner正确提到的那样__func__不是一个宏,它是一个特殊的函数 - 局部预定义变量。我取得了理想的结果

#define S1(x) #x
#define S2(x) S1(x)
#define LOCATION string(__func__) + " : " S2(__LINE__) + " : "

我通过将字符串发送到包装器日志功能来使用它

void log(string s) {
     cout << s <<endl;
}

void abc(){
    log(LOCATION + string("some message "));
}

输出:

abc : 23 : some message 

0
投票
__func__ is a variable (not a macro unlike __FILE__ or __LINE__)

这个相关的问题Treating __func__ as a string literal instead of a predefined identifier有很好的解释。

© www.soinside.com 2019 - 2024. All rights reserved.