Visual Studio 2017一直在不必要地重新编译stdafx.h

Visual Studio 2017 keeps recompiling stdafx.h needlessly?

本文关键字:编译 stdafx 新编译 2017 Studio 一直 不必要 Visual      更新时间:2023-10-16

我有一个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认识到其他文件不需要重新编译?

原来我一年前禁用了预编译头文件(但在项目中保留了stdafx.hstdafx.cpp),当我想再次使用它们时,我忘记打开/YcYu选项。

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

此外,我对预编译头文件的工作方式也有错误的认识。我以为stdafx.h会自己编译(然后通过一些中间表示转储到#include "stdafx.h"的.cpp文件中),但实际上编译的文件是stdafx.cpp(编译时会生成.pch文件)。(根据这个问题。)

打开预编译头选项后,当我修改header2.cpp时,只有code2.cpp会重新编译,正如我所希望的那样。

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