预处理字符串连接

Preprocessing string concatenation

我想连接后面的 3 个字符串以产生良好的调试输出,方法是在之后使用 std::setw()。

__ FILENAME__ , ":" and LINE

#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)

#define AT __FILENAME__ ":" __LINE__

#ifdef DEBUG
    #ifdef VERBOSE
       #define printDebug(x) std::cout << AT << x << std::flush
    #else
       #define printDebug(x) std::cout << x << std::flush
    #endif
#else
    #define printDebug(x)
#endif

但实际上我收到错误消息说“;” “:”之前缺少字段。有人有想法吗?

我实际上是这样调用 printDebug() 函数的:

printDebug("[SUCCESS] Receiving Message");

您可以将 字符串文字 并排放置。

":" 是字符串文字。

__LINE__ 扩展为数字文字,而不是字符串一。

__FILENAME__ 根本不会扩展为文字。它扩展为一个表达式。

有一种方法可以从 __LINE__ 中获取字符串文字,但您不能使 __FILENAME__ 成为字符串文字。


你根本不需要在这里使用文字连接。你可以简单地这样做:

#ifdef VERBOSE
#define printDebug(x) std::cout << __FILENAME__ << ":" << __LINE__ << x << std::flush