包含预编译头时出错

Error including precompiled header

本文关键字:出错 编译 包含预      更新时间:2023-10-16

我正在windows 7上使用Visual studio 2010为控制台应用程序编写代码。我已经包含了其中使用的库,但当我只使用头文件构建程序时,它无法包含"stdafx.h"头文件。这是我的密码。

#include "stdafx.h"
#include "stgetriggersample.h"
int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

我得到这个错误:

error C1189: #error :  "include 'stdafx.h' before including this file for PCH"

"stdafx.h"头文件存在于我的当前目录中。

更新"stgetriggersample.h"的内容是

// StGETriggerSample.h : main header file for the PROJECT_NAME application
//
//#include"stdafx.h"
#pragma once
#ifndef __AFXWIN_H__
#include"stdafx.h"
    #error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h"       // main symbols

// CStGETriggerSampleApp:
// See StGETriggerSample.cpp for the implementation of this class
//
class CStGETriggerSampleApp : public CWinApp
{
public:
    CStGETriggerSampleApp();
// Overrides
    public:
    virtual BOOL InitInstance();
// Implementation
    DECLARE_MESSAGE_MAP()
};
extern CStGETriggerSampleApp theApp;

"stdafx.h"的内容是:

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>

// TODO: reference additional headers your program requires here

我尝试使用选项不使用预编译头编写代码,但仍然出现了相同的错误。

如何纠正这种情况。感谢

也许你一直在努力解决这个问题,事实上,你已经破坏了一些东西。让我们来了解一下Visual Studio中预编译头的正确配置(我将使用VS2012中的选项名称):

  1. 启用PCH的使用:项目属性->Configuration Properties->C/C++->Precompiled Headers->Precompiled Header->Use (/Yu)

  2. 设置预编译头的名称:项目属性->Configuration Properties->C/C++->Precompiled Headers->Precompiled Header File。在您的情况下,您应该看到标准PCH名称(stdafx.h)。如果你愿意,你可以改变它。

  3. (事实上,最重要的一步)启用PCH生成:标头是不够的。您还需要一个.cpp文件,负责生成PCH内容(因为只能编译源文件)。在这种情况下,您的项目附带了默认的stdafx.cpp。用人民币点击,然后:Configuration Properties->C/C++->Precompiled Headers->Precompiled Header->Create (/Yc)

从现在起,附加到您的项目的每个源文件(包括步骤3中负责PCH生成的源文件)的第一行非空行应该是这样的:

#include "PCH_NAME"

其中PCH_NAME是在步骤2中设置的预编译头的名称。

在所有这些设置都以这种方式设置后,我建议您:

  1. 清洁您的解决方案
  2. 检入Output DirectoryIntermediate Directory的项目属性路径。删除它们(我希望它们不包含任何代码——它们不应该包含)
  3. 在解决方案文件夹(*)中,您还应该看到名称为:your solution name-cc50b4e6的文件夹。删除它

这将使你的解决方案(包括IntelliSense数据库等)完全重置。然后,打开你的项目并编译它。

(*)-在解决方案文件夹中,默认情况下。如果您有有效的Fallback Location集合,它将被放置在那里。

在代码中:

#ifndef __AFXWIN_H__
    #include"stdafx.h"
    #error "include 'stdafx.h' before including this file for PCH"
#endif

看起来StGETriggerSample.h正在通过查找编译保护宏AFXWIN_h__来检查stdafx.h是否已被#包含。然而,stdafx.h实际上并没有定义这个保护宏,它只是依靠语句"#pragmaonce"来避免多个包含。因此,即使stdafx.h已经包含在内,#error语句也将始终触发。

要修复此问题,请添加编译保护

#ifndef __STDAFX_H__
#define __STDAFX_H__
// ... yadda yadda yadda...
#endif // __STDAFX_H__

您可以从stdafx.h中删除#pragmaonce语句,但这不是必须的。

顺便说一句,如果代码还没有包含stdafx.h,那么它也会尝试#include,但无论如何都会导致编译错误。我敢肯定你只想做其中一个。。。