VC編譯時出現C1189 #error WINDOWS.H already included. MFC apps must not #include 的解決方法


  • 參考鏈接

c++ - #error WINDOWS.H already included. MFC apps must not #include <windows.h> - Stack Overflow

  • 背景

因為項目需要用到Windows截屏功能,要求代碼是C++的。於是使用到了VC的MFC相關的類。但是項目在編譯時出現了

#error WINDOWS.H already included. MFC apps must not #include <windows.h>。

  • 原因分析

在使用的MFC一些頭文件中已經包含了windows.h頭文件。再次聲明時出現了以上錯誤信息。如果你在VS中雙擊錯誤信息。會帶你相應的報錯的頭文件中。如下。

根據宏可以知道,如果聲明了_WINDOWS_的話,將會報出#error后面的信息,程序編譯中止。而_WINDOWS_正是windows.h頭文件中防止多次聲明使用的字符串。

// afxv_w32.h - target version/configuration control for Win32

#pragma once

#ifdef _WINDOWS_
#error WINDOWS.H already included. MFC apps must not #include <Windows.h>
#endif
View Code

 頭文件windows.h,部分

#include <winapifamily.h>

/*++ BUILD Version: 0001    Increment this if a change has global effects

Copyright (c) Microsoft Corporation. All rights reserved.

Module Name:


    windows.h

Abstract:

    Master include file for Windows applications.

--*/

#ifndef _WINDOWS_
#define _WINDOWS_
......
View Code

 

  • 解決方法

解決方法無非就是讓mfc的頭文件優先聲明,這樣在加入windows.h頭文件的時候,由於windows.h中已經存在防止重復聲明的宏,就不會再出錯。

1.將所有 afx開頭的mfc頭文件放在頭文件中的最前方。#include <Windows.h>放在頭文件聲明的最下方。

注意,編譯的時候是從main函數開始的。所以,afx開頭的頭文件應該盡量放在main函數的頭文件引用的最上方。

在調整完順序之后,刪除工程所有的debug文件和release文件。重新rebuild一次。

例子

#include <afxwin.h>
#include <atlimage.h>
#include <atlbase.h>
#include <atlconv.h>
#include <atltypes.h>

#include <vector>
#include <fstream>
#include <ostream>
#include <exception>

#include <Windows.h>
View Code

 2.如果你的項目很大,頭文件很多的話,可能無法准確弄清楚哪個頭文件先包含了windows.h頭。

你可以在VS2017中,打開showIncludes選項,這樣編譯過程中加載頭文件的順序就會被打印出來。你可以慢慢調整。

  1. 項目的“屬性頁
  2. 選擇“C/C++”文件夾。
  3. 單擊“高級”屬性頁。
  4. 修改“顯示包含”屬性。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM