32

我有一个 Visual C++ 6 中的示例项目(不是我的)。我正在尝试将其转换为 Visual Studio 2008。

较旧的项目使用预编译的头文件。现在的问题是:

  1. 什么是预编译头文件?

  2. 由于旧项目使用的是预编译头文件。我还将在 Visual Studio 2008(新项目)中使用它们。但是我收到错误消息说“您忘记包含 stdafx.h”,为了解决这个问题,我在每个源文件中都包含“stdafx.h”。那工作得很好。但是旧项目没有在每个文件中都包含“stdafx.h”?那么我如何选择退出在每个源文件中包含“stdafx.h”。因为不是每个源文件都需要“stdafx.h”中定义的包含文件,所以只有少数需要。这是怎么做的?

编辑: 我如何从使用预编译头文件中排除某些文件?

4

3 回答 3

56

什么是预编译头文件?

C++ 源文件通常包含来自外部库的头文件。在 Windows 中,您包括windows.h. 这些头文件可能非常大,需要一些时间来处理。每次编译 C++ 文件时,编译器都必须从这些头文件中读取和处理数千行。但是外部库不会改变,如果您只处理这些文件一次并保存结果,您可以节省大量时间。

预编译的头文件只是一堆头文件,它们已经被处理成中间形式,以后可以被编译器一次又一次地使用。

Visual C++ 中的预编译头文件

在 Visual C++ 中,习惯于将#include所有不变的头文件放在stdafx.h. 然后,您指示编译器在编译时创建预编译头文件,该头文件stdafx.pch除了stdafx.cppinclude 之外什么都不做stdafx.h。如果您想在另一个.cpp文件中使用预编译头文件,您必须将其包含stdafx.h为第一个包含文件,并指示编译器将其stdafx.pch用于您的预编译头文件。

如果您收到关于不包含的错误,stdafx.h您只需指示编译器不要为该特定源文件使用预编译头文件。(或者你可以包括stdafx.h。)

单个源文件的预编译头设置

Visual C++ 允许您控制整个项目和单个文件的编译器设置。要访问单个属性,请在解决方案资源管理器中选择源文件,右键单击它并从上下文菜单中选择属性。预编译头文件的选项位于Configuration Properties => C/C++ => Precompiled Headers。如果您修改这些设置,您通常会希望对所有配置(例如DebugRelease)执行此操作。

当您使用预编译头文件时,您将对整个项目进行设置,指示编译器将其stdafx.pch用于预编译头文件。将stdafx.cpp有一个单独的设置,指示编译器生成stdafx.pch,如果您有一些不包含的源文件,stdafx.h您可以在这些上设置单独的设置以不使用预编译头文件。

于 2009-08-18T12:41:13.770 回答
5

编译代码时,编译器必须查看所有#included 标头以了解如何编译 .cpp 文件中的代码。

对于大型项目(或使用 MFC 等库的项目),这些头文件可能会变得很大,因此需要很长时间才能编译。

Because most of these headers don't change that often (if ever), you can get the compiler to "precompile" them - it processes them and saves its state into a precompiled header. THe next time it compiles, it doesn't need to read and compile all those headers again, so it is much faster.

One requirement in Visual Studio is that if you use a precompiled header, it must be included in every file in the project.

If the project is small, or you don't build it often, then you can just disable the "precompiled header" option (in the project settings. This applies to the whole project). The only effect you'll get is that it may compile more slowly. Or leave the option enabled and just add #include "stdafx.h" as the first include in every file.

于 2009-08-18T12:41:32.787 回答
0
  1. See MSDN
  2. Usually. you need to include "stdafx.h" in every cpp file. The whole point is that they are precompiled, and you don't need to worry that not all of them are used in some concrete file.
于 2009-08-18T12:42:42.867 回答