萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C++ 宏字串化 #val 在 Unicode 環境下的正確用法

問題現象

常見除錯宏:

#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()(正常顯示,無亂碼)。

原理深度解析

延伸:通用 ANSI/Unicode 宏寫法

#ifdef UNICODE
    #define T_STR(x) L## #x
    #define T_COUT std::wcout
#else
    #define T_STR(x) #x
    #define T_COUT std::cout
#endif

#define CHECK(condition) T_COUT << _T("check failed: ") << T_STR(condition) << std::endl

搭配 _T() / TEXT() 宏,單一原始碼同時支援 ANSI/Unicode 建置。

常見誤區

  • ❌ L#condition — L 必須與字串字面常數相鄰,不能隔開 #。
  • ❌ #Lcondition — 字串化會將 L 視為字元一部分,產生 "Lcondition"。
  • ✅ L## #condition — 正確的 Token Pasting 順序。

適用場景

  • 除錯巨集輸出函式名稱、檔案行號(__FUNCTION__、__LINE__)。
  • 日誌框架統一輸出寬字串。
  • 跨平台專案以 TCHAR/_T 抽象字元型別。

掌握 L## # 技巧,讓除錯宏在 Unicode 專案中也能乾淨、正確地輸出中英文訊息。

copyright © 萬盛學電腦網 all rights reserved
階段處理結果
預處理#condition → 字串化"myfunc()"
預處理L## #condition → Token PastingL"myfunc()"
編譯寬字串字面常數const wchar_t[10]
連結/執行wcout 輸出正確 Unicode 文字