20

I read the documentation in MSDN, but in the end I didn't get a clear idea what is the practical difference between them, exactly. Both seem to require stdafx.h to be added at the top of every *.cpp file.

I'm using VS2008.

Can anyone help clear things up?

sashoalm
  • 75,001
  • 122
  • 434
  • 781
  • A link to the documentation might be relevant. The trivial absurd answer would be: *one is used to **create** the precompiled header, the other to **use** it* (i.e. one to have the compiler read the regular headers and generate the precompiled header, the other for the compiler not to generate the precompiled header but rather use it. – David Rodríguez - dribeas Jul 30 '12 at 13:57

2 Answers2

30

Short summary of how to use PCH files in Visual Studio:

  • All cpp files in the project have to include stdafx.h (you can change this to something else if you wish)
  • Select project in Solution Explorer and in Properties -> C++ -> Precompiled Headers set 'Create/Use precompiled headers' to 'Use'. Hit Apply
  • While the Property Pages are still shown select stdafx.cpp in solution explorer and set the value to 'Create'
the_mandrill
  • 29,792
  • 6
  • 64
  • 93
  • In addition to the short summary above, for each vc++ project in your solution where you are using precompiled headers, you should select the StdAfx.cpp file and set the Precompiled Header property to Create (/Yc). Then select all other cpp files in that project (select them all as a group with the shift+mouse) and in one go set the Precompiled Header property for them to Use (/Yu). – Philip Beck Apr 17 '19 at 11:25
  • 2
    You don't need to do that. If you follow the steps I listed above then it will set them all to Use and then you override the `stdafx.cpp` one to Create. – the_mandrill Jun 06 '19 at 13:48
14

Well, I think that you must first understand the purpose of precompiled headers. In large projects, it can take ages to process all the headers required by a single client extension for example, so some people prefer to distribute the .pch files along with their libraries. In order to generate the .pch files, you use the /Yc compiler flag and the person who wants to consume your library will set the /Yu flag. See here and here for details.

Mihai Todor
  • 8,014
  • 9
  • 49
  • 86
  • You shouldn't be getting PCH files from a library. For one thing, most code uses multiple libraries, yet the compiler can read only one PCH. For another, the headers used during library development are probably quite different from the ones needed by the consumer code. – Ben Voigt Jul 22 '16 at 20:40
  • @BenVoigt Indeed, that probably isn't a common practice. I've seen this done in a tightly sealed banking environment, where the code base was huge and the client extensions were strictly derived from stuff that got delivered by this company. Please feel free to suggest an edit if you think this answer needs improving. – Mihai Todor Jul 22 '16 at 23:02