用引号定义 C++ 预处理器宏

defining C++ preprocessor macro with quotation marks

我正在尝试在 C++ 中定义一个宏,它在变量周围加上引号。

我正在尝试做的一个简化示例是:

#define PE(x) std::cout << "x" << std::endl;

然后当我在我的代码中输入 PE(hello) 时,它应该打印 hello;但它只是打印 x.

我知道如果我成功了:

#define PE(x) std::cout << x << std::endl;

然后键入 PE("hello") 然后它会工作,但我希望能够在没有引号的情况下使用它。

这可能吗?

您可以使用字符串化运算符,#:

#define PE(x) std::cout << #x << std::endl;

不过,我建议您从宏中删除分号。所以,

#define PE(x) std::cout << #x << std::endl
...
PE(hello);