views:

719

answers:

4

Does every file need to #include "stdafx.h" when using precompiled headers? Or do only source files need to include it.

EDIT: Also, my precompiled header file #includes a lot of STL headers. But, in my headers, I sometimes have functions that return std::vector or something like that, so I need to #include <vector> anyway. Is this worse than including stdafx.h? I need to include the definitions for my unit testing framework.

+3  A: 

Every source file needs to include it before any non-comment line. Headers do not need to include it, as every source file will include it before any other header.

bdonlan
But what if source file from another project includes this header file? In this case stdafx.h from first project will not be included.
SMART_n
You're only allowed one precompiled header per project, and each _source file_ (don't include it from other header files!) must include it first. If you want to work with two projects with different precompiled header files, no problem - as long as they're separate projects. They'll each get their own header file, no conflict.
bdonlan
You don't understand me.Project 1:stdafx.h: #include <vector> ...One.h: vector<int> Some();One.cpp: #include "stdafx.h" #include "One.h" ....Project 2:Two.cpp:#include "One.h"In Two.cpp vector class is undefined, so we have error here.
SMART_n
Sorry for such text formating, comments dosn't support newlines here.
SMART_n
If you're asking something complex enough to need newlines, you should probably open a new question for it :) Feel free to link it here so I can take a look though.
bdonlan
A: 

You can set whether you want to use a precompiled header file or not at the project level or a file level. For the project setting, go to project properties dialog and click Configuration Properties / C/C++ / Precompiled Headers. There is an option for Create/Use Precompiled Header. You can overwrite the project level setting on each .cpp file by setting the same option on file properties dialog.

Kei
That was not the question....
rlbond
A: 

All you C/C++ files need to have your precompiled header at the top yes - if it set for that project. But you can have it turned off/on per C/C++ file (what Kei said).

If you have standard headers to include, place them all in the precompiled header. Then you want need them in the normal header (.h) files. As long as all projects and files are using precompiled headers.

Simeon Pilgrim
A: 

As other have said, only your source files need to include the precompiled header. I would only add that, in my opinion, code should compile correctly with or without precompiled headers. To achieve this, headers should be self contained and not rely on the source files including other required headers. I see precompiled header only as a way to speed up the compilation and not as a repository of all used headers in a project.

Bojan Resnik