我定义了以下一组宏(我从 How can I use the compile time constant __LINE__ in a string? 的第一个答案中得到),试图拥有一个宏“LOCATION_PREFIX”,我可以用它来“捕获”一行代码的位置(将传递给将执行日志记录的其他函数)。
#define STRINGIZE(f,l) STRINGIZE2(f) "(" STRINGIZE2(l)"):"
#define STRINGIZE2(x) #x
#define LOCATION_PREFIX STRINGIZE(__FILE__, __LINE__)
int main(){
printf("%s here\n", LOCATION_PREFIX);
printf("%s over here\n", LOCATION_PREFIX);
return 1;
}
输出:
"t.cpp"(8): here
"t.cpp"(9): over here
我希望输出为:
t.cpp(8): here
t.cpp(9): over here
非常感谢任何帮助!
最佳答案
您不需要第一个 STRINGIZE2
调用,因为文件名已经是一个带引号的字符串:
#define STRINGIZE(f,l) f "(" STRINGIZE2(l) "):"
#define STRINGIZE2(x) #x
#define LOCATION_PREFIX STRINGIZE(__FILE__, __LINE__)
int main(){
printf("%s here\n", LOCATION_PREFIX);
printf("%s over here\n", LOCATION_PREFIX);
return 1;
}
关于宏中的 C++ 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15527721/