Pre-Compiled Header (why need to include in every source file)

Viewed 51

I am trying to understand pre-compiled headers. So I set up the following sample project:

pch.hpp

#include <vector>

pch.cpp

#pragma once
#include "pch.hpp"

Vector.hpp

#pragma once
#include "pch.h"

class Vector {
public:
    Vector(const size_t N, const int init);

private:
    std::vector<int> m_data;
};

Vector.cpp

#pragma once
#include "pch.hpp"
#include "Vector.hpp"

Vector::Vector(const size_t N, const int init)
    : m_data(N, init) { }

Source.cpp

#include "pch.hpp"
#include "Vector.hpp"

int main() {
    const Vector v1(3, 5);
}

I did this in VS 2022 by marking pch.hpp as the pre-compiled header file under Project Properties --> C++ --> Pre-Compiled Headers --> Header File with Use (/Yu). And setting pch.cpp as Create (/Yc).

Now, when I remove #include "pch.hpp" in Vector.cpp or Source.cpp, I get this error:

File         Vector.cpp
Line         10
Severity     Error
Code         C1010
Description  unexpected end of file while looking for precompiled header.
             Did you forget to add '#include "pch.hpp"' to your source?

However, if I disable pre-compiled headers, everything compiles fine. As one would expect.

So, it seems that with pre-compiled headers enabled, I now need to put #include "pch.hpp" into every other source file? Even though #include "Vector.hpp" already includes pch.hpp? Is it possible to avoid having to put #include "pch.hpp" into all my other source files?

I ask, because I have a much larger code base (than the example above), and I thought I could essentially replace all instances of #include <vector> with #include "pch.hpp" and be done. But having to add #include "pch.hpp" to numerous cpp files, requires me to touch a lot of files (and seems counter-intuitive).

Apologies for the possibly naive question, as I am new to pre-compiled headers.

0 Answers
Related