在Visual Studio自動生成的項目中,碰見了一件關於文件編碼的問題,集中在類似於以下的語句上:
DASLog (DASProtWarn, L"(%s)消息超時,進入慢循環召喚模式。", GetHierarchyName());
編譯時會出現以下錯誤:
error C2001:常量中有換行符
該錯誤的原因很顯然是文件編碼的問題,在網上搜索了一下,找到了如下解決辦法:
(1)全部用英文編碼,不要用中文
(2)偶數中文 或 結尾加英文的符號,如"."
(3)將文件編碼進行一個手動(如記事本)轉換,改成UTF-8格式
我采用了第二種方式,直接將末尾的中文“。”改成了英文的“.”,該錯誤就解決了!
至於該問題的詳細原因,參考一位網友的分析說明(引用:http://www.cnblogs.com/cocos2d-x/archive/2012/02/26/2368873.html):
有個叫wva的人遇到過類似問題,他向微軟提交了此bug http://connect.microsoft.com/VisualStudio/feedback/details/341454/compile-error-with-source-file-containing-utf8-strings-in-cjk-system-locale 根據Visual C++ Compiler Team員工的解釋: The compiler when faced with a source file that does not have a BOM the compiler reads ahead a certain distance into the file to see if it can detect any Unicode characters - it specifically looks for UTF-16 and UTF-16BE - if it doesn't find either then it assumes that it has MBCS. I suspect that in this case that in this case it falls back to MBCS and this is what is causing the problem. 看見了吧,對於那些沒有BOM的文件設計就是這樣的。從語氣上看,他們編譯器小組也不打算修改設計。所以呢,在VC上使用“無簽名的UTF-8”編碼的文件,你就是在抱着一顆不定時炸彈玩耍。因為你永遠都不敢確定哪些詞能通過編譯,哪些不能! 如果要硬編碼字符串,即便是字符編碼轉換也不一定能幫不上你。一旦你為此增加了字符編碼轉換的代碼,那么也意味着可移植性降低了。因為這從根本上是編譯器決定的。