首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> 關於VC++

VC++ 編譯錯誤「找不到 xxx.pch」/「Unexpected end while looking for precompiled header」完整解決方案

     編輯:關於VC++

錯誤現象

  • cannot open precompiled header file 'Debug/xxx.pch'
  • Unexpected end of file while looking for precompiled header directive

根本原因

VC 使用 預編譯標頭 (Precompiled Header, PCH) 機制:

  1. stdafx.cpp 僅含 #include "stdafx.h"
  2. stdafx.h 包含常用系統標頭 (afxwin.h, windows.h, vector...)
  3. 編譯 stdafx.cpp 產生 xxx.pch (二進制語法樹快照)
  4. 其他 .cpp 開頭 #include "stdafx.h" 即可直接載入 PCH,大幅加速編譯

錯誤發生於:

  • .pch 檔遺失/損壞/版本不符
  • .cpp 未包含 #include "stdafx.h" (或順序錯誤)
  • 專案設定與實際檔案不一致

三種解決方案 (依推薦順序)

方案一:重建 PCH (最快、保留加速效果)

  1. 專案屬性 → C/C++ → Precompiled Headers
  2. Create/Use Precompiled Header → "Automatically generate (/YX)"
  3. Through Header → "stdafx.h"
  4. 清理解決方案 → 重新建置

VS 會自動偵測 .pch 是否存在/有效,無效則重建。

方案二:停用 PCH (除錯期適用、編譯較慢)

    專案屬性 → C/C++ → Precompiled Headers
  1. Create/Use Precompiled Header → "Not Using Precompiled Headers (/Y-)"
  2. 所有 .cpp 移除 #include "stdafx.h" (或保留亦無妨)

方案三:強制重建 / 手動刪除

  1. 關閉 VS
  2. 刪除專案目錄下 Debug/、Release/、ipch/、*.pch、*.ncb、*.suo
  3. 重開專案 → 重新建置

常見誤區與檢查清單

現象原因修正
新增 .cpp 忘記 #include "stdafx.h"PCH 要求第一個 non-comment 行必須是此 include加在檔案最開頭
stdafx.h 內容變更後未重建.pch 為舊版本方案一或清理重建
多專案共用 stdafx.h 但 PCH 設定不一致每專案獨立 PCH各專案單獨設定
使用 /clr (C++/CLI) 專案PCH 支援有限建議停用 PCH

進階小技巧:Incremental Link 導致的怪異行為

若編譯/連結無錯但執行邏輯異常、單步偵錯跳行錯誤:

  • 專案屬性 → Linker → General → Enable Incremental Linking → No (/INCREMENTAL:NO)
  • 或執行 Rebuild All (而非 Build)

增量連結為了速度保留舊目標檔片段,偶爾導致符號表/行號表不同步。

總結

  1. 預設選 Automatically generate (/YX) + stdafx.h → 最省心
  2. 遇到 PCH 錯誤 → Clean + Rebuild 解決 99%
  3. 除錯期可暫時停用 PCH 排除干擾
  4. Incremental Link 同理,怪異行為先 Rebuild
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved