常見除錯宏:
#define CHECK(condition) cout << "check failed:" << #condition << endl;
CHECK(myfunc()) 展開為 cout << "check failed:" << "myfunc()" << endl;,在 ANSI 建置正常;但在 **Unicode (UTF-16) 專案**中,字串字面常數預設為 wchar_t*,導致 #condition 產生窄字串,與寬字串流混用產生亂碼或編譯錯誤。
#define CHECK(condition) cout << L"check failed:" << L## #condition << endl;
L## #condition 利用 **Token Pasting (##)** 將 L 前綴與字串化結果合併,產生 L"myfunc()" 寬字串字面常數。L"check failed:" 同樣標記為寬字串,確保 wcout 或 cout(配合 std::locale)正確輸出。#include <iostream>
#define CHECK(condition) std::wcout << L"check failed: " << L## #condition << std::endl
bool myfunc() { return false; }
int main() {
std::locale::global(std::locale("")); // 支援中文顯示
if (!myfunc()) CHECK(myfunc());
return 0;
}
輸出:check failed: myfunc()(正常顯示,無亂碼)。
| 階段 | 處理 | 結果 |
|---|---|---|
| 預處理 | #condition → 字串化 | "myfunc()" |
| 預處理 | L## #condition → Token Pasting | L"myfunc()" |
| 編譯 | 寬字串字面常數 | const wchar_t[10] |
| 連結/執行 | wcout 輸出 | 正確 Unicode 文字 |