设置一个项目,该项目将使用和不使用预编译头文件进行编译

Setting up a project which would compile both with and without precompiled header

我想做的是建立一个项目,其中是否设置预编译头都无关紧要。 stdafx.hpp 是我的 P.H.

我的主要问题是我有多个目录的文件,而不仅仅是项目根目录。我尝试了什么:

  1. 如果我

    #include "stdafx.hpp"
    

    设置 PH 后到处都能正常工作,但如果我停用它,它会抱怨,因为子目录中的文件找不到它。

  2. 如果我

    #include "../stdafx.hpp"
    

    在子目录中的文件中,没有 PH 也能正常工作,但是有了 PH,编译器会抱怨 stdafx.hpp 没有被包含。

  3. 如果我将强制包含文件设置为 stdafx.hpp,无论是相对路径还是绝对路径,编译器都会给我错误(现在不记得了,如果有必要我会重现它) .

那么,解决方案是什么?

规范的解决方案很简单:不包含预编译的 header 文件(默认为 stdafx.h)。如果您的代码需要使用预编译的 headers 进行编译,请使用 /FI (Name Forced Include File) 编译器开关:

This option has the same effect as specifying the file with double quotation marks in an #include directive on the first line of every source file specified on the command line, in the CL environment variable, or in a command file.

这允许您使用预编译的 header 文件,而无需修改您的源代码。

使用带双引号的#include 指令的规则在 #include Directive (C/C++):

下概述

Quoted form:

The preprocessor searches for include files in this order:

  1. In the same directory as the file that contains the #include statement.
  2. In the directories of the currently opened include files, in the reverse order in which they were opened. The search begins in the directory of the parent include file and continues upward through the directories of any grandparent include files.
  3. Along the path that's specified by each /I compiler option.
  4. Along the paths that are specified by the INCLUDE environment variable.

使用 /I (Additional Include Directories) 编译器开关来包含用于生成预编译 header 的 header 文件的目录,这样您就可以编写

/FIstdafx.hpp

没有任何 settings/project 拓扑组合可以让您简单地打开或关闭预编译的 header。 /Y, /FI, and /I compiler switches must be used together, or removed entirely. To change a set of configurations as a unit, you can use property pages (see Working with Project Properties 了解详情)。

一个简单的解决方案是设置项目的包含路径,以便普通 #include "stdafx.hpp" 总能找到 header,而不管包含文件的目录如何。

如果您担心无意中使其他目录中的 header 文件可见,您甚至可以将可能预编译的 header 放在其自己的特殊目录中。