Question

I've inherited some code that did something like this,

Header: HeaderFile.h

#ifndef HEADERFILE_H
#define HEADERFILE_H

#ifndef HEADERFILE_PCH_H
#include<LibStuff>
#include<LibStuff2>
#include<LibStuff3>
#include<LibStuff4>
#include<LibStuff5>
#endif

#include "FilesInProject"

Class A
{
  //Code

};

#endif

Cpp: HeaderFile.cpp

#include "HeaderFile_pch.h" //(1)

#include "HeaderFile.h"

//More code

I understand what a precompiled header is for and what the code is doing here (sort of). When I copy these files into my project, this is so I can update deprecated code but not effect the original project, VS2010 chocks on line (1). VS2010 Saying it can't find that file.

I've gone between the two projects and I can't find any differences in settings.

What am I missing and why is it okay to imbed PCH's in headers like this instead of actually moving them to a file called HeaderFile_pch.h. Is this some kind of macro hack?

Was it helpful?

Solution

For starters, there is no such file as Headerfile_pch.h either in the samples you provided above nor likely on your local fs.

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" but can be anything you choose. All files will get this setting (thus the configuration at the project level) EXCEPT....

One file is responsible for generating the PCH file. That file is typically the stdafx.cpp file in your project, but again, it can be whatever single source you desire. Most just setup a dummy cpp file that has one thing in it: #include "myheader.h" (duh).. 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 that source file is recompiled first to regenerate the PCH data file before the others are kicked off.

The one attribute of this that is absolutely mandatory: that include header (myheader.h or whatever you're calling it) must be the first include in any source file you're compiling that is participating in using pch including (hopefully obviously) the file you specified as the "generator" (the one marked as "Create" in the prior paragraph).

Lastly, you can disable pch on a file-by-file basis if this is a problem due to unusual conditions in your build environment (i.e. 3rd party headers that do stupid things).

There are other ways of configuring PCH setting in Visual Studio, but this is by far the most common.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top