Precompiled headers, re-including files and Intellisense - c++

I have a precompiled header that contains includes for various 3rd party libraries, e.g.:
#ifndef PRECOMPILED_H
#define PRECOMPILED_H
#include "booststuff.h"
#include "luastuff.h"
#endif
Where booststuff.h and luastuff.h are header files in my project that just include various boost / lua related things and set up some typedefs / usings / namespace aliases.
I set up the precompiled header in the usual way inside visual studio (2012), and use the force include option to include it in every cpp file.
In the cpp files, I've also been fairly careful to #include "booststuff.h" where I actually use it as well (I sometimes disable precompiled headers to test this). However, I've been wondering lately whether that's a good idea. So:
Does anything bad happen if I include a file again that's already included in the precompiled header (I don't see why it would, but I've seen things about headers having to be included "in the same order", and not really understood what they were on about)?
Does it affect Intellisense (unusably slow with a fairly small project)? I'd be happy to give up some portability for better Intellisense since I currently have no desire to switch platforms.

If each include file has #pragma once in it, the compiler will completely skip reading the file on the second and subsequent attempts to include it. It isn't stated explicitly but I assume the precompiled header tracks this information as well.

Related

System headers before other headers according to Google Style guide? [duplicate]

What order should include files be specified, i.e. what are the reasons for including one header before another?
For example, do the system files, STL, and Boost go before or after the local include files?
I don't think there's a recommended order, as long as it compiles! What's annoying is when some headers require other headers to be included first... That's a problem with the headers themselves, not with the order of includes.
My personal preference is to go from local to global, each subsection in alphabetical order, i.e.:
h file corresponding to this cpp file (if applicable)
headers from the same component,
headers from other components,
system headers.
My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #included without prerequisites (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.
The big thing to keep in mind is that your headers should not be dependent upon other headers being included first. One way to insure this is to include your headers before any other headers.
"Thinking in C++" in particular mentions this, referencing Lakos' "Large Scale C++ Software Design":
Latent usage errors can be avoided by ensuring that the .h file of a component parses by itself – without externally-provided declarations or definitions... Including the .h file as the very first line of the .c file ensures that no critical piece of information intrinsic to the physical interface of the component is missing from the .h file (or, if there is, that you will find out about it as soon as you try to compile the .c file).
That is to say, include in the following order:
The prototype/interface header for this implementation (ie, the .h/.hh file that corresponds to this .cpp/.cc file).
Other headers from the same project, as needed.
Headers from other non-standard, non-system libraries (for example, Qt, Eigen, etc).
Headers from other "almost-standard" libraries (for example, Boost)
Standard C++ headers (for example, iostream, functional, etc.)
Standard C headers (for example, cstdint, dirent.h, etc.)
If any of the headers have an issue with being included in this order, either fix them (if yours) or don't use them. Boycott libraries that don't write clean headers.
Google's C++ style guide argues almost the reverse, with really no justification at all; I personally tend to favor the Lakos approach.
I follow two simple rules that avoid the vast majority of problems:
All headers (and indeed any source files) should include what they need. They should not rely on their users including things.
As an adjunct, all headers should have include guards so that they don't get included multiple times by over-ambitious application of rule 1 above.
I also follow the guidelines of:
Include system headers first (stdio.h, etc) with a dividing line.
Group them logically.
In other words:
#include <stdio.h>
#include <string.h>
#include "btree.h"
#include "collect_hash.h"
#include "collect_arraylist.h"
#include "globals.h"
Although, being guidelines, that's a subjective thing. The rules on the other hand, I enforce rigidly, even to the point of providing 'wrapper' header files with include guards and grouped includes if some obnoxious third-party developer doesn't subscribe to my vision :-)
To add my own brick to the wall.
Each header needs to be self-sufficient, which can only be tested if it's included first at least once
One should not mistakenly modify the meaning of a third-party header by introducing symbols (macro, types, etc.)
So I usually go like this:
// myproject/src/example.cpp
#include "myproject/example.h"
#include <algorithm>
#include <set>
#include <vector>
#include <3rdparty/foo.h>
#include <3rdparty/bar.h>
#include "myproject/another.h"
#include "myproject/specific/bla.h"
#include "detail/impl.h"
Each group separated by a blank line from the next one:
Header corresponding to this cpp file first (sanity check)
System headers
Third-party headers, organized by dependency order
Project headers
Project private headers
Also note that, apart from system headers, each file is in a folder with the name of its namespace, just because it's easier to track them down this way.
I recommend:
The header for the .cc module you're building. (Helps ensure each header in your project doesn't have implicit dependencies on other headers in your project.)
C system files.
C++ system files.
Platform / OS / other header files (e.g. win32, gtk, openGL).
Other header files from your project.
And of course, alphabetical order within each section, where possible.
Always use forward declarations to avoid unnecessary #includes in your header files.
I'm pretty sure this isn't a recommended practice anywhere in the sane world, but I like to line system includes up by filename length, sorted lexically within the same length. Like so:
#include <set>
#include <vector>
#include <algorithm>
#include <functional>
I think it's a good idea to include your own headers before other peoples, to avoid the shame of include-order dependency.
This is not subjective. Make sure your headers don't rely on being #included in specific order. You can be sure it doesn't matter what order you include STL or Boost headers.
First include the header corresponding to the .cpp... in other words, source1.cpp should include source1.h before including anything else. The only exception I can think of is when using MSVC with pre-compiled headers in which case, you are forced to include stdafx.h before anything else.
Reasoning: Including the source1.h before any other files ensures that it can stand alone without it's dependencies. If source1.h takes on a dependency on a later date, the compiler will immediately alert you to add the required forward declarations to source1.h. This in turn ensures that headers can be included in any order by their dependants.
Example:
source1.h
class Class1 {
Class2 c2; // a dependency which has not been forward declared
};
source1.cpp
#include "source1.h" // now compiler will alert you saying that Class2 is undefined
// so you can forward declare Class2 within source1.h
...
MSVC users: I strongly recommend using pre-compiled headers. So, move all #include directives for standard headers (and other headers which are never going to change) to stdafx.h.
Include from the most specific to the least specific, starting with the corresponding .hpp for the .cpp, if one such exists. That way, any hidden dependencies in header files that are not self-sufficient will be revealed.
This is complicated by the use of pre-compiled headers. One way around this is, without making your project compiler-specific, is to use one of the project headers as the precompiled header include file.
Several separate considerations are conflated when deciding for a particular include order. Let try to me untangle.
1. check for self-containedness
Many answers suggest that the include order should act as a check that your headers are self-contained. That mixes up the consideration of testing and compilation
You can check separately whether your headers are self-included. That "static analysis" is independent of any compilation process. For example, run
gcc headerfile.h -fsyntax-only
Testing whether your header files are self-contained can easily be scripted/automated. Even your makefile can do that.
No offense but Lakos' book is from 1996 and putting those different concerns together sounds like 90s-style programming to me. That being said, there are ecosystems (Windows today or in the 90s?) which lack the tools for scripted/automated tests.
2. Readability
Another consideration is readability. When you look up your source file, you just want to easily see what stuff has been included. For that your personal tastes and preferences matter most, though typically you either order them from most specific to least specific or the other way around (I prefer the latter).
Within each group, I usually just include them alphabetically.
3. Does the include order matter?
If your header files are self-contained, then the include order technically shouldn't matter at all for the compilation result.
That is, unless you have (questionable?) specific design choices for your code, such as necessary macro definitions that are not automatically included. In that case, you should reconsider your program design, though it might work perfectly well for you of course.
It is a hard question in the C/C++ world, with so many elements beyond the standard.
I think header file order is not a serious problem as long as it compiles, like squelart said.
My ideas is: If there is no conflict of symbols in all those headers, any order is OK, and the header dependency issue can be fixed later by adding #include lines to the flawed .h.
The real hassle arises when some header changes its action (by checking #if conditions) according to what headers are above.
For example, in stddef.h in VS2005, there is:
#ifdef _WIN64
#define offsetof(s,m) (size_t)( (ptrdiff_t)&(((s *)0)->m) )
#else
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
Now the problem: If I have a custom header ("custom.h") that needs to be used with many compilers, including some older ones that don't provide offsetof in their system headers, I should write in my header:
#ifndef offsetof
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
And be sure to tell the user to #include "custom.h" after all system headers, otherwise, the line of offsetof in stddef.h will assert a macro redefinition error.
We pray not to meet any more of such cases in our career.

When do i want to turn off "precompiled header" in visual studio?

First of all i want to say that I read about precompiled headers and I understand that this is an optimization that saves me the time of compiling headers over and over on every built.
I'm reading the documentation of boost and I see that in the instructions they say:
In Configuration Properties > C/C++ > Precompiled Headers, change Use Precompiled Header (/Yu) to Not Using Precompiled Headers
And then they explain it:
There's no problem using Boost with precompiled headers; these instructions merely avoid precompiled headers because it would require Visual Studio-specific changes to the source code used in the examples.
Can some explain me the sentence I marked in bold? which visual studio specific changes they are talking about ? (Here is the link to the documentation I'm reading: http://www.boost.org/doc/libs/1_55_0/more/getting_started/windows.html#pch)
Why and when I would want to turn off the precompiled headers?
what is the difference between "Create" and "Use" in the precompiled header options.
Originally a comment, but I may as well post it. Note: this is specific to VC++:
The bold sentence is their way of saying the samples don't follow the mantra of a unified use-this-lead-in-header-for-pch-generation model. IOW, their samples aren't PCH-friendly, but you can still use pch with boost in your projects if properly configured.
You would turn them off for a variety of reasons. Some source modules, particularly ones from 3rd-parties, don't follow the PCH model of including "the" pch-through-header at their outset. Their samples are such code (and thus the advise to turn them off for their samples). Sometimes source files require different preprocessor configurations only for this files and not all files int he project; another reason to disable PCH for those files.
You typically use a source/header pair to generate "the One"; the precompiled header image. This header file typically includes:
Any system standard lib headers used by your project
3rd-party SDK headers
Just about everything else that is NOT in active development for your project.
The single source file tagged as Create typically includes one line of code : #include "YourHeaderFile.h", where YourHeaderFile.h is the header you filled with stuff from the list above. Tagging it as "Create" through header YourHeaderFile.h tells VC it is the file needed for rebuilding the PCH through that header when compiling other source files. All other source files are tagged as Use (except the ones where PCH is turned off) and should include, as their first line of code, the same #include "TheHeaderFile.h".
In short (hard to believe), <boost> is telling you their samples aren't setup like described above, and as such you should turn PCH off when building them.
When you use pre-compiled headers, you need to do something like:
#include <foo>
#include <bar>
#include <baz>
#pragma hdrstop
// other code here
Everything before the #pragma goes into the precompiled header. Everything after it depends on the precompiled header. The VC++ specific "magic" to make pre-compiled header work is that #pragma.
There's a little more to the story than just that though. To make pre-compiled headers work well, you want to include exactly the same set of headers in exactly the same order in every source file.
That leads to (typically) creating one header that includes all the other common headers and has the #pragma hdrstop right at its end, then including that in all the other source files.
Then, when the compiler does its thing, there are two phases: first you need to create a pre-compiled header. This means running the compiler with one switch. The compiler only looks at what comes before the #pragma hdrstop, builds a symbol table (and such) and puts the data into a .pch file.
Then comes the phase when you do a build using the pre-compiled header. In this phase, the compiler simply ignores everything in the the file up to the #pragma hdrstop. When it gets to that, it reads the compiler's internal state from the .pch file, and then starts compiling that individual file.
This means each source file typically includes a lot of headers it doesn't actually need. That, in turn, means that if you don't use pre-compiled headers, you end up with compilation that's much slower than if you hadn't done anything to support pre-compiled headers at all.
In other words, although the only part that's absolutely required is the #pragma hdrstop, which is fairly innocuous, a great deal more file re-structuring is needed to get much benefit from them--and those changes are likely to actively harmful to compilation time if you're using anything that doesn't support pre-compiled headers (and in the same way VC++ does them at that).
When precompiled headers is on every cpp source file must start with #include "stdafx.h"
So you would turn it off if you do not want to edit all the boost source files.
When precompiled headers is on stdafx.cpp "creates" the precompiled header. All other files "use" the precompiled header.

C/C++ include header file order

What order should include files be specified, i.e. what are the reasons for including one header before another?
For example, do the system files, STL, and Boost go before or after the local include files?
I don't think there's a recommended order, as long as it compiles! What's annoying is when some headers require other headers to be included first... That's a problem with the headers themselves, not with the order of includes.
My personal preference is to go from local to global, each subsection in alphabetical order, i.e.:
h file corresponding to this cpp file (if applicable)
headers from the same component,
headers from other components,
system headers.
My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #included without prerequisites (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.
The big thing to keep in mind is that your headers should not be dependent upon other headers being included first. One way to insure this is to include your headers before any other headers.
"Thinking in C++" in particular mentions this, referencing Lakos' "Large Scale C++ Software Design":
Latent usage errors can be avoided by ensuring that the .h file of a component parses by itself – without externally-provided declarations or definitions... Including the .h file as the very first line of the .c file ensures that no critical piece of information intrinsic to the physical interface of the component is missing from the .h file (or, if there is, that you will find out about it as soon as you try to compile the .c file).
That is to say, include in the following order:
The prototype/interface header for this implementation (ie, the .h/.hh file that corresponds to this .cpp/.cc file).
Other headers from the same project, as needed.
Headers from other non-standard, non-system libraries (for example, Qt, Eigen, etc).
Headers from other "almost-standard" libraries (for example, Boost)
Standard C++ headers (for example, iostream, functional, etc.)
Standard C headers (for example, cstdint, dirent.h, etc.)
If any of the headers have an issue with being included in this order, either fix them (if yours) or don't use them. Boycott libraries that don't write clean headers.
Google's C++ style guide argues almost the reverse, with really no justification at all; I personally tend to favor the Lakos approach.
I follow two simple rules that avoid the vast majority of problems:
All headers (and indeed any source files) should include what they need. They should not rely on their users including things.
As an adjunct, all headers should have include guards so that they don't get included multiple times by over-ambitious application of rule 1 above.
I also follow the guidelines of:
Include system headers first (stdio.h, etc) with a dividing line.
Group them logically.
In other words:
#include <stdio.h>
#include <string.h>
#include "btree.h"
#include "collect_hash.h"
#include "collect_arraylist.h"
#include "globals.h"
Although, being guidelines, that's a subjective thing. The rules on the other hand, I enforce rigidly, even to the point of providing 'wrapper' header files with include guards and grouped includes if some obnoxious third-party developer doesn't subscribe to my vision :-)
To add my own brick to the wall.
Each header needs to be self-sufficient, which can only be tested if it's included first at least once
One should not mistakenly modify the meaning of a third-party header by introducing symbols (macro, types, etc.)
So I usually go like this:
// myproject/src/example.cpp
#include "myproject/example.h"
#include <algorithm>
#include <set>
#include <vector>
#include <3rdparty/foo.h>
#include <3rdparty/bar.h>
#include "myproject/another.h"
#include "myproject/specific/bla.h"
#include "detail/impl.h"
Each group separated by a blank line from the next one:
Header corresponding to this cpp file first (sanity check)
System headers
Third-party headers, organized by dependency order
Project headers
Project private headers
Also note that, apart from system headers, each file is in a folder with the name of its namespace, just because it's easier to track them down this way.
I recommend:
The header for the .cc module you're building. (Helps ensure each header in your project doesn't have implicit dependencies on other headers in your project.)
C system files.
C++ system files.
Platform / OS / other header files (e.g. win32, gtk, openGL).
Other header files from your project.
And of course, alphabetical order within each section, where possible.
Always use forward declarations to avoid unnecessary #includes in your header files.
I'm pretty sure this isn't a recommended practice anywhere in the sane world, but I like to line system includes up by filename length, sorted lexically within the same length. Like so:
#include <set>
#include <vector>
#include <algorithm>
#include <functional>
I think it's a good idea to include your own headers before other peoples, to avoid the shame of include-order dependency.
This is not subjective. Make sure your headers don't rely on being #included in specific order. You can be sure it doesn't matter what order you include STL or Boost headers.
First include the header corresponding to the .cpp... in other words, source1.cpp should include source1.h before including anything else. The only exception I can think of is when using MSVC with pre-compiled headers in which case, you are forced to include stdafx.h before anything else.
Reasoning: Including the source1.h before any other files ensures that it can stand alone without it's dependencies. If source1.h takes on a dependency on a later date, the compiler will immediately alert you to add the required forward declarations to source1.h. This in turn ensures that headers can be included in any order by their dependants.
Example:
source1.h
class Class1 {
Class2 c2; // a dependency which has not been forward declared
};
source1.cpp
#include "source1.h" // now compiler will alert you saying that Class2 is undefined
// so you can forward declare Class2 within source1.h
...
MSVC users: I strongly recommend using pre-compiled headers. So, move all #include directives for standard headers (and other headers which are never going to change) to stdafx.h.
Include from the most specific to the least specific, starting with the corresponding .hpp for the .cpp, if one such exists. That way, any hidden dependencies in header files that are not self-sufficient will be revealed.
This is complicated by the use of pre-compiled headers. One way around this is, without making your project compiler-specific, is to use one of the project headers as the precompiled header include file.
Several separate considerations are conflated when deciding for a particular include order. Let try to me untangle.
1. check for self-containedness
Many answers suggest that the include order should act as a check that your headers are self-contained. That mixes up the consideration of testing and compilation
You can check separately whether your headers are self-included. That "static analysis" is independent of any compilation process. For example, run
gcc headerfile.h -fsyntax-only
Testing whether your header files are self-contained can easily be scripted/automated. Even your makefile can do that.
No offense but Lakos' book is from 1996 and putting those different concerns together sounds like 90s-style programming to me. That being said, there are ecosystems (Windows today or in the 90s?) which lack the tools for scripted/automated tests.
2. Readability
Another consideration is readability. When you look up your source file, you just want to easily see what stuff has been included. For that your personal tastes and preferences matter most, though typically you either order them from most specific to least specific or the other way around (I prefer the latter).
Within each group, I usually just include them alphabetically.
3. Does the include order matter?
If your header files are self-contained, then the include order technically shouldn't matter at all for the compilation result.
That is, unless you have (questionable?) specific design choices for your code, such as necessary macro definitions that are not automatically included. In that case, you should reconsider your program design, though it might work perfectly well for you of course.
It is a hard question in the C/C++ world, with so many elements beyond the standard.
I think header file order is not a serious problem as long as it compiles, like squelart said.
My ideas is: If there is no conflict of symbols in all those headers, any order is OK, and the header dependency issue can be fixed later by adding #include lines to the flawed .h.
The real hassle arises when some header changes its action (by checking #if conditions) according to what headers are above.
For example, in stddef.h in VS2005, there is:
#ifdef _WIN64
#define offsetof(s,m) (size_t)( (ptrdiff_t)&(((s *)0)->m) )
#else
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
Now the problem: If I have a custom header ("custom.h") that needs to be used with many compilers, including some older ones that don't provide offsetof in their system headers, I should write in my header:
#ifndef offsetof
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
And be sure to tell the user to #include "custom.h" after all system headers, otherwise, the line of offsetof in stddef.h will assert a macro redefinition error.
We pray not to meet any more of such cases in our career.

C++ Header order [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
What order should headers be declared in a header / cpp file? Obviously those that are required by subsequent headers should be earlier and class specific headers should be in cpp scope not header scope, but is there a set order convention / best practice?
In a header file you have to include ALL the headers to make it compilable. And don't forget to use forward declarations instead of some headers.
In a source file:
corresponded header file
necessary project headers
3rd party libraries headers
standard libraries headers
system headers
In that order you will not miss any of your header files that forgot to include libraries by their own.
Good practice: every .h file should have a .cpp that includes that .h first before anything else. This proves that any .h file can be put first.
Even if the header requires no implementation, you make a .cpp that just includes that .h file and nothing else.
This then means that you can answer your question any way you like. It doesn't matter what order you include them in.
For further great tips, try this book: Large-Scale C++ Software Design - it's a shame it's so expensive, but it is practically a survival guide for C++ source code layout.
In header files, I tend to put standard headers first, then my own headers (both lists being ordered alphabetically). In implementation files, I put first the header corresponding (if any), then standards headers and other dependency headers.
Order is of little importance, except if you make a great use of macros and #define ; in that case, you must checked that a macro you defined doesn't replace a previously included one (except if that's what you want, of course).
Concerning this statement
those that are required by subsequent headers should be earlier
A header shouldn't rely on other headers being included before it! If it requires headers, it just includes them. Header guards will prevent multiple inclusion:
#ifndef FOO_HEADER_H
#define FOO_HEADER_H
...
#endif
EDIT
Since I wrote this answer, I changed my way of ordering the include directives in my code. Now, I try to always put headers in increasing order of standardization, so the headers of my project come first, followed by 3rd party libraries headers, followed by standard headers.
For instance, if one of my file uses a library I wrote, Qt, Boost and the standard library, I will order the includes as follow:
//foo.cpp
#include "foo.hpp"
#include <my_library.hpp>
// other headers related to my_library
#include <QtCore/qalgorithms.h>
// other Qt headers
#include <boost/format.hpp> // Boost is arguably more standard than Qt
// other boost headers
#include <algorithms>
// other standard algorithms
The reason why I do that is to detect missing dependencies in my own headers: let's assume for instance that my_library.hpp uses std::copy, but doesn't include <algorithm>. If I include it after <algorithm> in foo.cpp, this missing dependency will go unnoticed. On the contrary, with the order I just presented, the compiler will complain that std::copy has not been declared, allowing me to correct my_library.hpp.
In each "library" group, I try to keep the include directives ordered alphabetically, to find them more easily.
On a sidenote, a good practice is also to limit at a maximum the dependency between header files. Files should include as little headers as possible, especially headers file. Indeed, the more headers you include, the more code needs to be recompiled when something changes. A good way to limit these dependencies is to use forward declaration, which is very often sufficient in header files (see When can I use a forward declaration?).
Google C++ Style Guide, Names and Order of Includes :
In dir/foo.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows:
dir2/foo2.h (preferred location — see details below).
C system files.
C++ system files.
Other libraries' .h files.
Your project's .h files.
I used to order them in alphabetical order (easier to find)
The "how" is not obvious, but the "what" is.
Your goal is to make sure that the order in which you include header files never matters (and i mean "NEVER !").
A good help is to test whether header files compile when building cpp files (one for each header file) that only include one of them.
For .cpp files, you should include the header of the class or whatever you are implementing first, so you catch the case where this header is missing some includes. After that, most coding guidelines tend to include system headers first, project headers second, for example the Google C++ Style Guide.
It's a dependency thing and it depends largely on what you put in our headers. A fact is that you can be really notorious about this and minimize to keep your includes strict but you'll eventually run into a scenario where you'll wanna use inclusion guards.
#ifndef MY_HEADER_H
#define MY_HEADER_H
//...
#endif
The problem isn't that apparent in the beginning, but as the complexity of your software grows so does your dependencies. You can do well, and be smart about it but larger C++ projects are generally riddled with includes. You can try, but you can only do so much. So be diligent and think about your includes, YES! But you'll most certainly have cyclic dependencies at some point and that is why you need inclusion guards.
If a header needs other headers then it just includes them in that header.
Try to structure your code so you pass pointers or references and forward declare where you can.
In the implementation then the header that defines it should be listed first (except in Visual Studio if you are using pch then stdafx would go first).
I generally list them as I need.
I've found the following convention the most useful:
module.cpp:
// this is the header used to trigger inclusion of precompiled headers
#include <precompiled.h>
// this ensures that anything that includes "module.h" works
#include "module.h"
// other headers, usually system headers, the project
The important thing is to put the module's header as the first non-precompiled header. This ensures "module.h" has no unexpected dependencies.
If you're working on a large project with slow disk access times, I've seen this style used to decrease build times:
module.cpp:
// this is the header used to trigger inclusion of precompiled headers
#include <precompiled.h>
// this ensures that anything that includes "module.h" works
#include "module.h"
// other headers, usually system headers, the project
#if !defined _OTHER_MODULE_GUARD_
#include "other_module.h"
#endif
#if !defined _ANOTHER_MODULE_GUARD_
#include "another_module.h"
#endif
It's a bit verbose but does save on disk seeking since the header won't be searched for / opened if it's already been included. Without the guard check, the compiler will seek for and open the header file, parse the whole file to end up #ifdefing the whole file out.

Is there a way to use pre-compiled headers in VC++ without requiring stdafx.h?

I've got a bunch of legacy code that I need to write unit tests for. It uses pre-compiled headers everywhere so almost all .cpp files have a dependecy on stdafx.h which is making it difficult to break dependencies in order to write tests.
My first instinct is to remove all these stdafx.h files which, for the most part, contain #include directives and place those #includes directly in the source files as needed.
This would make it necessary to turn off pre-compiled headers since they are dependent on having a file like stdafx.h to determine where the pre-compiled headers stop.
Is there a way to keep pre-compiled headers without the stdafx.h dependencies? Is there a better way to approach this problem?
Yes, there is a better way.
The problem, IMHO, with the 'wizard style' of precompiled headers is that they encourage unrequired coupling and make reusing code harder than it should be. Also, code that's been written with the 'just stick everything in stdafx.h' style is prone to be a pain to maintain as changing anything in any header file is likely to cause the whole codebase to recompile every time. This can make simple refactoring take forever as each change and recompile cycle takes far longer than it should.
A better way, again IMHO, is to use #pragma hdrstop and /Yc and /Yu. This enables you to easily set up build configurations that DO use precompiled headers and also build configurations that do not use precompiled headers. The files that use precompiled headers don't have a direct dependency on the precompiled header itself in the source file which enables them to be build with or without the precompiled header. The project file determines what source file builds the precompiled header and the #pragma hdrstop line in each source file determines which includes are taken from the precompiled header (if used) and which are taken directly from the source file... This means that when doing maintenance you would use the configuration that doesn't use precompiled headers and only the code that you need to rebuild after a header file change will rebuild. When doing full builds you can use the precompiled header configurations to speed up the compilation process. Another good thing about having the non-precompiled header build option is that it makes sure that your cpp files only include what they need and include everything that they need (something that is hard if you use the 'wizard style' of precompiled header.
I've written a bit about how this works here: http://www.lenholgate.com/blog/2004/07/fi-stlport-precompiled-headers-warning-level-4-and-pragma-hdrstop.html (ignore the stuff about /FI) and I have some example projects that build with the #pragma hdrstop and /Yc /Yu method here: http://www.lenholgate.com/blog/2008/04/practical-testing-16---fixing-a-timeout-bug.html .
Of course, getting from the 'wizard style' precompiled header usage to a more controlled style is often non-trivial...
When you normally use precompiled headers, "stdafx.h" serves 2 purposes. It defines a set of stable, common include files. Also in each .cpp file, it serves as a marker as where the precompiled headers end.
Sounds like what you want to do is:
Leave precompiled header turned on.
Leave the "stdafx.h" include in each .cpp file.
Empty out the includes from "stdafx.h".
For each .cpp file, figure out which includes were needed from the old "stdafx.h". Add these before the #include "stdafx.h" in each .cpp file.
So now you have the minimal set of dependancies, and you still are using precompiled headers. The loss is that you are not precompiling your common set of headers only once. This would be a big hit for a full rebuild. For development mode, where you are only recompiling a few files at a time, it would be less of a hit.
No, there is probably NOT a better way.
However, for a given individual .cpp file, you might decide that you don't need the precompiled header. You could modify the settings for that one .cpp file and remove the stdafx.h line.
(Actually, though, I don't how the pre-compiled header scheme is interferring with the writing of your unit tests).
No. pre-compiled headers relies on a single header included by all sources compiled this way.
you can specify for a single source (or all) not to use pre-compiled headers at all, but that's not what you want.
In the past, Borland C++ compiler did pre-compilation without a specific header. however, if two sources files included the same headers but at different order, they were compiled separately, since, indeed, the order of header files in C++ can matter...
Thus it means that the borland pre-compiled headers did save time only if you very rigidly included sources in the same order, or had a single include file included (first) by all other files... - sounds familiar ?!?!
Yes. The "stdafx.h/stdafx.pch" name is just convention. You can give each .cpp its own precompiled header. This would probably be easiest to achieve by a small script to edit the XML in your .vcproj. Downside: you end up with a large stack of precompiled headers, and they're not shared between TU's.
Possible, but smart? I can't say for sure.
My advice is - don't remove precompiled headers unless you want to make your builds painfully slow. You basically have three options here:
Get rid of precompiled headers (not recommended)
Create a separate library for the legacy code; that way you can build it separately.
Use multiple precompiled headers within a single project. You can select individual C++ files in your Solution Explorer and tell them which precomiled header to use. You would also need to setup your OtherStdAfx.h/cpp to generate a precompiled header.
Pre-compiled headers are predicated on the idea that everything will include the same set of stuff. If you want to make use of pre-compiled headers then you have to live with the dependencies that this implies. It comes down to a trade-off of the dependencies vs the build speed. If you can build in a reasonable time with the pre-compiled headers turned off then by all means do it.
Another thing to consider is that you can have one pch per library. So you may be able to split up your code into smaller libraries and have each of them have a tighter set of dependencies.
I only use pre-compiled headers for the code that needs to include the afx___ stuff - usually just UI, which I don't unit-test. UI code handles UI and calls functions that do have unit-tests (though most don't currently due to the app being legacy).
For the bulk of the code I don't use pre-compiled headers.
G.
Precompiled headers can save a lot of time when rebuilding a project, but if a precompiled header changes, every source file depending on the header will be recompiled, whether the change affects it or not. Fortunately, precompiled headers are used to compile, not link; every source file doesn't have to use the same pre-compiled header.
pch1.h:
#include <bigHeader1.h>
#include ...
pch1.cpp:
#include "pch1.h"
source1.cpp:
#include "pch1.h"
[code]
pch2.h:
#include <bigHeader2.h>
#include ...
pch2.cpp:
#include "pch2.h"
source2.cpp
#include "pch2.h"
[code]
Select pch1.cpp, right click, Properties, Configuration Properties, C/C++, Precompiled Headers.
Precompiled Header : Create(/Yc)
Precompiled Header File: pch1.h
Precompiled Header Output File: $(intDir)pch1.pch
Select source1.cpp
Precompiled Header : Use(/Yu)
Precompiled Header File: pch1.h
Precompiled Header Output File: $(intDir)pch1.pch (I don't think this matters for /Yu)
Do the same thing for pch2.cpp and source2.cpp, except set the Header File and Header Output File to pch2.h and pch2.pch. That works for me.