PCH compiler options for MSVC - c++

I am a bit confused about when to use /Yc (create PCH) as opposed to /Yu (use PCH.) For a project that has never used precompiled headers in the past, naturally, the PCH file will not exist initially. Am I supposed to fire off a initial build with /Yc, have it create the PCH file and then change the setting to /Yu for all subsequent builds?
That can't possibly be it, right?

Try this: Create a header to contain all the headers to pre-compile eg: stdafx.h (this MUST be the 1st include in all .cpp files). File to generate the PCH: stdafx.cpp which only includes stdafx.h and compile this with /Yc. All other .cpp files include stdafx.h at the start and compile with /Yu. MSVC is clever enough to do the /Yc file 1st.

Related

referencing the precompiled header from a subfolder causes build to fail [duplicate]

With "Show all files" option on in VS, i added a folder and created a new class in that folder. Since i'm using precompiled headers i also need to include the stdafx.h that's in the root directory relative to the new class file.
In my cpp file i have
#include "..\stdafx.h"
Yet I get the following error:
error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?
My understanding is, that the .. should instruct the compiler to go one directory level up ?
Visual C++ allows you to define several ways of setting up precompiled header files. The most common is to enable it for ALL source files at the project configuration level, Under Configuration Properties/C++/Precompiled Headers, setting "Precompiled Header", select "Use". The same location, setting "Precompiled Header File", is usually "stdafx.h". All files will get this setting (thus the configuration at the project) EXCEPT....
One file is responsible for generating the PCH file. That file is typically the stdafx.cpp file in your project, and it typically has nothing in it except #include "stdafx.h". Configuring Precompiled Headers for THAT ONE FILE, switch from "Use" to "Create". This ensures that if the prime-header for PCH gets out of synch stdafx.cpp is ALWAYS compiled first to regenerate the PCH data file. There are other ways of configuring PCH setting in Visual Studio, but this is the most common.
That being said, your problem is definitely irritating. The filename used to prime the PCH system and specified on both the "Use..." and "Create..." setting above MUST MATCH THE TEXT IN YOUR #include EXACTLY.
Therefore, it is highly likely you can address your problem by adding ".." to your project include directories and removing the ".." from your #include statement. you could also change it at the project-configuration level to be "..\stdafx.h" as the through-header, but that might be a problem if you have source files in multiple folders hierarchically.
Oh, and if it wasn't clear to you while perusing the PCH configuration settings, if you do NOT want to use PCH for any specific source file (and there are reasons not to sometimes) you can turn it OFF for specific source files, otherwise be sure to always have #include "your-pch-include-file.h" at the head of every source file (c/cpp,etc).
Hope you catch a break.
I generally also like to have a hierarchical order in my projects, and I've found there are two simple ways to include a precompiled header:
Either
Put the directory where stdafx.h lies into the compiler's include directories.
(Properties - VC++ Directories - Include Directories: Add $(ProjectDir))
Or
If there aren't too many subdirectories, a simple way to circumvent the error message is like this:
Put an stdafx.h file into each of your subdirectories which only includes the top-level stdafx.h:
#include "..\stdafx.h"
Write #include "stdafx.h" as first line of all source files in your subdirectories, instead of including the top-level file there.
This way, all your code files use the same precompiled header file, and there is no other complicated setup to do.
It's interesting that the trick that I use isn't in the answers:
Create stdafx.h and stdafx.cpp in the root folder of the project.
Go to project properties -> precompiled headers. Change to "use".
Go to stdafx.cpp, right-click properties -> precompiled headers. Change to "create".
Go to project properties -> advanced; change "Force include files" to stdafx.h;%(ForcedIncludeFiles)
Don't change any CPP file; keep your header files as they are. Build as-is.
No typing, no RSI, no hassle with include paths, no other pain and misery. And the beauty is that it will still work when you move your solution to another platform. Awesome.
You can adjust the precompiled header settings on a per-file basis.
In Solution Explorer right click on the .cpp file, select "Properties".
I'd strongly recommend selecting "All Configurations" in the Configuration drop down List item.
Browse to "C/C++" - "Precompiled Headers".
Adjust the "Precompiled Header File" from "stdafx.h" to whatever you need (in your case for example "../stdafx.h").
Note this is tedious and error prone since it's done on a per-file basis, and future developers adding files to your project will have to follow the same steps. If they don't they will be faced with warnings and errors such as:
warning C4627: '#include "<path>"': skipped when looking for
precompiled header use.
and
fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?
which don't give much indication as to this or any other approach.
I guess they'll eventually turn to StackOverflow and end up here... Hello, thanks for reading.
On that basis, it's worth going with alternatives, such as putting $(ProjectDir) on the C++ Include path (under C++\General) but then that can cause confusion when including other header files.
PCH files are wierd, and even moreso in Visual Studio. When compiling a .cpp file that uses a PCH, VS expects the first non-comment/whitespace text to be #include "PCH_NAME_HERE". The PCH_NAME_HERE is exactly the PCH's name. No directories, nothing. Just the PCH's name as specified in the compiler options.
If you're going to do this directory fudging, then you need to modify your compiler settings so that the directory where the PCH is is in the directory search path. That way, you don't need to have the ..\ part.
I would suggest to use:
$(ProjectDir)/pch/my_pch.h
as "Precompiled Header File"
and "Advanced > Force Include File"
This will auto include pch for your .cpp files in the beginning, so nothing needs to be changed in the .cpp files.
And this is better than changing the include directory, because sometimes you might have multiple pch files in the include directories, and then you can't tell which one has been used.
The cause of the confusion is that Visual Studio treats the include directive that includes the precompiled header differently to other include directives. Specifically it does not look for the precompiled header using the normal path lookup approach, instead it simply attempts to match the include directive to that defined in the project configuration by simple string comparison.
Precompiler header configuration is set gobally but can be overridden per file. The normal global config (accessed via Project Properties -> Configuration Properties -> C/C++ -> Precompiled Headers) is:
Precompiled Header: Use (/Yu)
Precompiled Header File: stdafx.h
Precompiled Header Output File: $(IntDir)$(TargetName).pch
This configuration is applied to all files in the project by default. However the config for stdafx.cpp is set at the file level and overrides the Precompiled Header value to:
Precompiled Header: Create (/Yuc)
The effect of this is that for any source file configured to use the precompiled header (which by default is all of them except stdafx.cpp) VS will look for an include directive that matches the configured Precompiled Header File value. e.g.
#include "stdafx.h"
Because the check uses a simple string comparison instead of any kind of directory search, then (irrespective of the location of the source file relative to the project root directory or the location of the stdafx.h file) the path and filename used in the include directive must match exactly that used by the project's Precompiled Header File configuration setting. The unexpected side effect of this is that if you have a project subdirectory containing various source files, in those files you do not need to reference the stdafx.h file using a relative path like ..\stdafx.h (and if you do VS will raise an error stating that it encountered the end of file while looking for the precompiled header).
Just use the unadorned #include "stdafx.h" and it will work fine because VS will then recognise this as the directive to use the precompiled header, and it already knows where the correct precompiled header is because of stdafx.cpp Precompiled Header configuration being set to "Create (/Yc)".
If .cpp and .h files of your project live in different subdirectories (not plainly in the directory of the project), it would be a good coding style to use include paths relative to the solution directory (if you don't use a dedicated include directory). Particularly if you have multiple projects in a solution and need to share include files (e.g. for interoperability between projects, e.g. an .exe and a .dll).
To refactor your project you need to do the following:
In each project specify additional include directory
$(SolutionDir) : right-click on project, click "Properties", go to
"Configuration Properties"->"C/C++"->"General" (to do this for all
configurations at once, select "All Configurations" from the
"Configuration" dropdown)
Go to "C/C++"->"Precompiled Headers"
and change "Precompiled Header File" value to the path relative to
the solution directory, e.g. PROJECT_NAME/stdafx.h
In your .cpp
files include "PROJECT_NAME/stdafx.h", instead of just "stdafx.h"
In your .h and .cpp files, when including something, use path as
"PROJECT_NAME/dir1/dir2/file.h", except when including file from the
same directory
Using quotes means it is a header file you own use <> means it is a system header file if I am not mistaken just use #include <stdafx.h> and let the compiler find it

Visual Studio 2017 keeps recompiling stdafx.h needlessly?

I have a Visual Studio 2017 C++ project which uses precompiled headers (stdafx.h).
My (simplified) file structure is as follows:
header1.hpp
header2.hpp
stdafx.h -> includes header1.hpp
code1.cpp -> includes stdafx.h
code2.cpp -> includes stdafx.h and header2.hpp
To avoid any ambiguity, by saying includes header1.hpp, I mean there is a line #include <header1.hpp> in the file.
After I modify stdafx.h, all three files stdafx.h, code1.cpp and code2.cpp are recompiled (as expected).
After I modify code1.cpp, only code1.cpp is recompiled (as expected).
After I modify header2.cpp, all three files stdafx.h, code1.cpp and code2.cpp are recompiled (not expected!).
I would have expected item 3 to compile only code2.cpp, and not everything else.
A possible reason for this behavior would be that the build manager can't inspect and follow #include directives, so it simply recompiles everything if any header file is modified.
Since my project is quite large, recompiling all the files like code1.cpp takes up a significant amount of time. I purposely did not include header2.hpp from stdafx.h because I know I would modify header2.hpp often and only code2.cpp needs to use it. (header2.hpp is a template library that has functions only code2.cpp needs.)
Is this behavior expected, and what can I do to get Visual Studio to recognize that the other files need not be recompiled?
Turns out I had disabled precompiled headers a year ago (but left stdafx.h and stdafx.cpp in the project), and when I wanted to use them again I forgot to turn on the /Yc and Yu options.
No errors were given, and Visual Studio had been compiling stdafx.cpp like a regular .cpp file.
Also, I had the wrong idea of how precompiled headers worked. I thought stdafx.h gets compiled by itself (then dumped into those .cpp files that #include "stdafx.h" via some intermediate representation), but actually the file that gets compiled is stdafx.cpp (and while compiling produces the .pch file). (As per this question.)
After turning on the precompiled header options, when I modify header2.cpp, only code2.cpp gets recompiled, as I would like.
Also, compilation times are now significantly faster.

Precompiled headers - necessary to remove all precompiled headers from all other files

I have a very big project and for the sake of compilation speed I started to test precompiled headers.
I've setup everything now:
enable precompiled headers in VS (use them for the project, create it for the StdAfx.honly)
use multi processor compilation for all but for the StdAfx.h
automatically include the StdAfx.h in all my files via the force include of VS
The question that occurs now is following:
Do I need to remove all includes of all project files that I've added to the StdAfx.h file or is this unnecessary? Will the compiler skip any include automatically because he knows it's part of the StdAfx.h or should I remove them from each .h/.cpp file manually?
The good practice is to make each file include all the headers directly required by this file. This way changing includes in particular file should effect only this file. If you start depending on headers included somewhere else it will make your project structure extremely fragile. And the single "common includes" file is an extreme case of such scenario. Use of precompiled header supposed to speedup compilation by prebuilding commonly included header files, but project files should never assume that something is already included there. So there is no need need to remove includes from ".h/.cpp", actually there are some tools that will populate precompiled header based on includes in project files. Compiler will skip files already included in precompiled header (or in other headers) because of header guards.

Why does Visual Studio C++ require including "StdAfx.h" even on files that don't need it?

I understand what precompiled headers are doing with "#include "StdAfx.h" and yes, I know I can turn them off. But that's not my question.
If you're using precompiled headers, Visual C++ requires every cpp file to #include "StdAfx.h", even the files that aren't using any of the headers in StdAfx.h. If you forget to include StdAfx.h on one file, it's an error. But why? The obvious approach would be just "If you include StdAfx.h then that file will use it, but if you forget to include it, then those header files will simply not be included." I don't understand why VC++ would require you to include StdAfx.h when it's not needed. Seems like it would have been easier for them to treat it like a normal header file.
Is there any good reason why this is required?
Just a addition to the Marks answer. In fact, you do not have to manually include stdafx.h in the all project source files. You may use project option Forced Include Files:
That way stdafx.h will be automatically included in all your sources.
Your project default is "use precompiled headers". You can set individual files to "not use precompiled headers" if you desire.
In fact, stdafx.cpp itself has a different option from the project defaults:
What this configuration is saying is "start compiling this file (stdafx.cpp), stop when you finish compiling the statement that includes stdafx.h" and save the precompiled information as as .pch file." Visual studio is also smart enough to compile this file first so it is available for use.
The project defaults are:
What this configuration is saying is "For each compiled file, start with the precompiled data in the specified .pch and start compiling new information after the point stdafx.h is included." That's important and why stdafx.h should be included as the first line of the file. It will still work if you put it later in the file, but anything before the #include is ignored because that data won't be in the .pch. Absence of the #include means VS will scan the whole file looking for the pre-compiled starting location and not find it...generating an error.
If you have a file that you don't want to use pre-compiled information, you can select the file and override it. Example:
Visual Studio won't use the precompiled information and won't look for a header to include.
When you select the file, right-click properties, go to the "C/C++ \ Precompiled Headers" section and set "Precompiled Header" to "Not using Precompiled Headers", be sure that the Configuration (top left) is applicable to the current selected build.
It doesn't always automatically select the "active" configuration; so you could be setting the option for a non-active configuration so you will continue to experience the error ;)

Does visual C++ check if it needs to re-generate its pch if I use /Yc

It seems that when I set the option to /Yu, it just uses whatever pch there is, without checking if it needs to be updated, meaning it would keep a list of headers it precompiles and check if those files has been updated since the last time they have been precompiled.
But when I /Yc, it just re-precompiles each time I build my project.
I'm not very sure if visual C++ handles those behaviors as good as I think, or if I'm making the mistake of editing a .h file or else.
So should I set /Yc, build, reset to /Yu, keep iterating, but reset to /Yc, rebuild, and then RESET to /YU each time I update a header ?
You set one file that includes your header that you want precompiling to use /Yc, and that will generate the pch file if necessary (i.e., the pch file is out of date relative to the header). Then set the other files that include it to use /Yu, and they use the precompiled header that your first file generates.
If you use the Visual Studio wizard to generate a console project with a precompiled header, you'll see this in action. The stdafx.cpp file includes stdafx.h, and has /Yc set to generate a pch file for it; then the main.cpp file includes stdafx.h too, but it has /Yu set, so it uses the pch file.
(I found the precompiled header section of the documentation a bit opaque at first, but once I'd got precompiled headers set up and I'd seen them working, it started to make a bit more sense.)