c++ - 打印宏连接失败

标签 c++ macros

<分区>

我想创建一个宏来打印一些信息,并在需要时采用任意数量的参数来打印其他消息。

这是我正在谈论的代码片段:

#include <stdio.h>

#define print(msg, ...) \
    printf("Line: %d File %s "## msg, __LINE__ , __FILE__, __VA_ARGS__);

int main()
{
    print("Msg: %d", 13);
    print("Msg: %d, Msg2: %d", 123, 234);
}

这是我遇到的一个错误:

main.cpp:12:9: error: pasting ""Line: %d File %s "" and ""Msg: %d"" does not give a valid preprocessing token
  printf("Line: %d File %s "## msg, __LINE__ , __FILE__, __VA_ARGS__);

我做错了什么?

最佳答案

C 字符串文字会自动连接。您现在拥有的 ## 是为了将两个“标记”(不是字符串)合二为一,例如取 ABCXYZ 并使 ABCXYZ 作为标识符。

你想要这个:

printf("Line: %d File %s " msg, __LINE__ , __FILE__, __VA_ARGS__);

关于c++ - 打印宏连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51401066/

相关文章:

iphone - undefined symbol : . objc_class_name_UIScreen

c++ - C++ 中的 OpenCV Canny 视频边缘检测

linux - Vim:如何使用 .config 使未编译的行变暗

javascript - Macro Express Pro JavaScript 中的 VBScript echo 等效项

macros - 是否可以创建一个宏来计算扩展项目的数量?

python - 对于http请求,python比c++更快吗?

c++ - 如何拥有具有类型和大小的可变模板?

c++ - 无法编译 Intel Pin

c++ - Visual Studio 从预定义字符串宏中抛出 "undeclared identifier"

javascript - Umbraco Macro Referenced Root 但在重定位后现在已损坏