如何有效地使用预编译头(使用 /Yc 和 Yu 选项)?
我们使用 Visual Studio 2003 (VC71) 进行编译。 为了减少编译时间,我们更改了构建脚本,以便为每个 CPP 文件生成预编译头 (.pch) 文件。
makefile 中使用的选项:
/Yc"StdAfx.h"
/Fp"StdAfx.pch"
这样目标的编译时间减少了 30%。但是任何人都可以帮助我了解如何减少编译时间,即使每次编译每个 CPP 文件时都会生成 pch 文件。
另外,这是正确的方法吗?我们应该使用 Yc 和 Yu 组合吗? 我无法使用 /Yu 选项,因为 pch 文件应该至少生成一次。
We are using Visual Studio 2003 (VC71) for compilation.
In order to reduce the compile time we changed the build script such that it generates the precompiled header (.pch) file for each CPP file.
The option used in makefile:
/Yc"StdAfx.h"
/Fp"StdAfx.pch"
With this the compile time for the target got reduced by 30%. But could anyone help me to understand how is it reducing the compiler time even when the pch file is getting generated every time for compilation of each CPP file.
Also, is it the right approach? Should we use Yc and Yu combination ?
I cannot use /Yu option as the pch file should be genrated at least once.
问题
假设您有一个使用的标头列表,并且您知道这些标头不会更改。例如,C 头文件、C++ 头文件或 Boost 头文件等。
为每个 CPP 文件编译读取它们需要时间,并且这不是生产时间,因为编译器一次又一次地读取相同的头文件,并生成对于那些相同的头文件,一次又一次的相同的编译结果。
应该有某种方法告诉编译器这些标头始终相同,并缓存它们的编译结果而不是一次又一次地重新编译它们,不是吗?
解决方案
“预编译头”考虑到了这一点,因此您所需要做的就是:
现在,您需要告诉编译器 StdAfx.cpp 是包含通用且不变的头文件的空源代码。
这是使用标志 /Yc 和 /Yu 的地方:
编译器将生成(需要时)预编译头文件来自 StdAfx.cpp 文件,然后为所有其他标有 /Yu 的文件重用此预编译头文件。
注意
当您创建新项目时,旧版本的 Visual C++(如果我没记错的话,6 和 2003)将默认激活预编译头。最近的功能提供了激活或不激活的选择。
您应该在激活 PCH 的情况下创建一个新的 VC++ 项目,以获得启用 PCH 的项目的工作版本,并研究编译选项。
有关 PCH 的详细信息,您可以访问以下 URL:
The problem
Let's say you have a list of headers you use that you know won't change. For example, the C headers, or the C++ headers, or Boost headers, etc..
Reading them for each CPP file compilation takes time, and this is not productive time as the compiler is reading the same headers, again and again, and producing the same compilation result for those same headers, again and again.
There should be some way to tell the compiler those headers are always the same, and cache their compiled result instead of recompiling them again and again, no?
The solution
The Pre-Compiled Headers takes that into account, so all you need is to:
And now, what you need is tell the compiler that StdAfx.cpp is the empty source that includes the common and unchanging headers.
This is where the flags /Yc and /Yu are used:
And the compiler will generate (when needed) a pre-compiled header file from the StdAfx.cpp file, and then reuse this pre-compiled header file for all other files marked with /Yu.
Note
When you create a new project, old versions of Visual C++ (6 and 2003, if I remember correctly) would activate the precompiled headers by default. Recent ones offer the choice of activating them of not.
You should create a new VC++ project with the PCH activated to have a working version of PCH-enabled project, and study the compilation options.
For more information about PCH, you can visit the following URL: