C++ – How to include the stdafx.h from the root directory

cvisual c++

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 ?

Best Answer

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.