Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual studio forces to include precompiled header file in all compilation units of the project?

When compiler compiles source (e.g. *.cpp) file, it creates object file (e.g. *.o), so that later it will be linked to other .o and .so (.lib files for Windows) files and will constitute the executable file.

Now for analogical situation for not compiling header files each time it creates some .pch files so that it will be linked it by the linker then.

Now if in the scope of a Visula Studio project it is defined a precompiled header, then why Visual Studio complains with an error (e.g. **fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "stdafx.h"' to your source?**) that the header file is not included into the .cpp file.

By summarizing, here are my questions:

  1. Why in each .cpp file the precompiled header of the project is necessary?
  2. How does the requirement of presence of precompiled header in each compilation unit optimizes the compilation process? In other words, what is the benefit of this requirement? (It could be up to the user to decide where to include, where not!)
  3. If precompiled header is included into a .cpp file, which uses only 2% of what is in .pch file, then the remaining 98% will be added to corresponding .o file to?
like image 374
Narek Avatar asked Sep 19 '12 10:09

Narek


1 Answers

Why in each .cpp file the precompiled header of the project is necessary?

Because you asked for it. If you don't want to use it then you need to change the option for the .cpp file. Right-click it, Properties, C/C++, Precompiled Headers, "Create/Use" = "Not using precompiled headers". The default setting is "Use". There's little point in doing this.

How does the precompiled header in each compilation unit optimizes the compilation process?

By not having to parse the #includes. Particularly useful when you #include <windows.h>. Time saved is in the order of seconds, on large projects with hundreds of .cpp files that adds up to many minutes. It is by far the cheapest way to speed up the compiler with no loss of quality on the generated code.

then the remaining 98% will be added to corresponding .o file to?

Of course not.

like image 143
Hans Passant Avatar answered Sep 28 '22 04:09

Hans Passant