Visual Studio 2017 一直在无谓地重新编译 stdafx.h?

Visual Studio 2017 keeps recompiling stdafx.h needlessly?

我有一个 Visual Studio 2017 C++ 项目,它使用预编译头文件 (stdafx.h)。

我的(简化)文件结构如下:

header1.hpp
header2.hpp
stdafx.h -> includes header1.hpp
code1.cpp -> includes stdafx.h
code2.cpp -> includes stdafx.h and header2.hpp

为了避免歧义,说 includes header1.hpp,我的意思是文件中有一行 #include <header1.hpp>

  1. 我修改stdafx.h后,stdafx.hcode1.cppcode2.cpp三个文件都重新编译了(如预期)。

  2. 我修改code1.cpp后,只有code1.cpp被重新编译(符合预期)。

  3. 我修改header2.cpp后,stdafx.hcode1.cppcode2.cpp三个文件都重新编译了(没想到! ).

我原以为第 3 项只能编译 code2.cpp,而不是其他所有内容。

此行为的一个可能原因是构建管理器无法检查和遵循 #include 指令,因此如果任何头文件被修改,它只会重新编译所有内容。

由于我的项目很大,像code1.cpp一样重新编译所有文件会占用大量时间。我故意不包含 stdafx.h 中的 header2.hpp 因为我知道我会经常修改 header2.hpp 并且只有 code2.cpp 需要使用它。 (header2.hpp 是一个模板库,只有 code2.cpp 需要的功能。)

这种行为是预期的吗?我可以做些什么来让 Visual Studio 认识到不需要重新编译其他文件?

原来我在一年前禁用了预编译的headers(但在项目中留下了stdafx.hstdafx.cpp),当我想再次使用它们时我忘了转在 /YcYu 选项上。

没有给出任何错误,Visual Studio 一直在像普通 .cpp 文件一样编译 stdafx.cpp

此外,我对预编译 header 的工作方式有错误的认识。我以为 stdafx.h 自己 编译 (然后通过某种中间表示转储到 #include "stdafx.h" 的那些 .cpp 文件中),但实际上编译的文件是 stdafx.cpp(并在编译时生成 .pch 文件)。 (根据 this question。)

打开预编译header选项后,当我修改header2.cpp时,只有code2.cpp被重新编译,如我所愿。

此外,编译时间现在显着加快。