问题
What is the proper way to use stdafx.h
, in terms of separating dependencies?
If I put everything in there, then my compiles are blazing fast, and all I need to say in any file is
#include "stdafx.h"
with the caveats that:
- I no longer know which files depend on which headers.
- It reduces modularity, making my code less reusable.
- I can no longer separate C
#include
s from C++ ones (e.g.cstring
versusstring.h
) without a great deal of pain. (Speaking of which, does this even matter?)
If I put nothing in there, I can organize everything well -- but then my compiles slow down dramatically.
If I put everything in there and also include every header in my individual files, then I get the best of both worlds, with the caveat that now I have to keep track of synchronization issues.
Is there a well-known/well-accepted solution to this problem?
回答1:
You shouldn't put your own header files in stdafx.h
since your code is likely to change and will cause your whole program to recompile.
I usually put standard headers and other libraries in there, such as all boost includes.
回答2:
When using precompiled headers, you should make sure your project compiles cleanly even without PCH present (so treat it as optimisation, not a replacement for includes in every TU). Aside from that, don't put absolutely everything in there (and more importantly, don't ever put headers from your own project — PCH should contain only those that don't change or change very rarely — system libraries, external dependencies), but rather try to keep most used/biggest things precompiled.
回答3:
Personally, I would rather have slower compilation than no idea (visibility) how dependencies are. However, there are limits to everything.
As each project has its own pre-compiled header file, so I'd just put common-to-all-includes in there. Say if a project uses some boost headers those would fit well there as they will be used by the whole project and you're not changing them. Hence, put rarely/never changing headers in pre-compiled headers such as system or third party stuff.
For compilation speed, I'd rather rely on as much as possible to forward-declare things, split into smaller libraries and try to see if things can be organized in a way where volatile code is not affecting recompilation of much other code.
回答4:
Yor compiler might have a "show includes" flag. Turn it on, and look for deeply nested include hierarchies that are repeated. Consider including one of the most shallow include files to your header for each such deep trees.
回答5:
Conditionally include the PCH's, then define something like "#define _PRE_COMPILE_" This way the original headers are still visible and the code is modular if you so need. An example of this would be to include
#ifdef _PRE_COMPILE_
#include "stdafx.h"
#elif
#include <iostream>
#include <cstring>
#endif
Include this at the beginning of every source file.
来源:https://stackoverflow.com/questions/7201904/how-to-use-stdafx-h-properly