Andrei Andrey Andrei Andrey - 1 month ago 4x
C++ Question

Setting up a project which would compile both with and without precompiled header

What I am trying to do is to set up a project in which wouldn't matter if precompiled header is set or not.

is my P.H.

My main problem is that I have files over serveral directories, not only project root directory. What have I tryed:

  1. If I

    #include "stdafx.hpp"

    everywhere works fine with PH set on, but it would complain if I deactivate it, because the files in the subdirectories coudn't find it.

  2. If I

    #include "../stdafx.hpp"

    in the files which are in subdirs, it works fine without PH, but with PH, the compiler complains about
    not being included.

  3. If I set force include file to
    , either with relative or absolute path, compiler gave me errors (can't rememeber right now, if it's necessary I will reproduce it).

So, what could be the solution?


The canonical solution is easy: Don't include the precompiled header file (stdafx.h by default). If your code needs to compile with precompiled headers, use the /FI (Name Forced Include File) compiler switch:

This option has the same effect as specifying the file with double quotation marks in an #include directive on the first line of every source file specified on the command line, in the CL environment variable, or in a command file.

This allows you to use precompiled header files, without modifying your source code.

The rules for using an #include directive with double quotation marks are outlined under #include Directive (C/C++):

Quoted form:

The preprocessor searches for include files in this order:

  1. In the same directory as the file that contains the #include statement.
  2. In the directories of the currently opened include files, in the reverse order in which they were opened. The search begins in the directory of the parent include file and continues upward through the directories of any grandparent include files.
  3. Along the path that's specified by each /I compiler option.
  4. Along the paths that are specified by the INCLUDE environment variable.

Using the /I (Additional Include Directories) compiler switch to include the directory of the header file used to generate the precompiled header would then simply allow you to write


There is no combination of settings/project topology that would allow you to simply toggle precompiled headers on or off. The /Y, /FI, and /I compiler switches must be used together, or removed entirely. To change a set of configurations as a unit, you can use property pages (see Working with Project Properties for details).