What is "stdafx.h" and what is its importance?

8

When creating a C ++ project in Visual Studio, it automatically brings a line in the main file:

#include "stdafx.h"

As I started the language study, seeing some " hello world ", I did not find this line in the examples.

When removing this line, 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?

What is the purpose of this line?

    
asked by anonymous 20.05.2017 / 03:20

2 answers

6

For lack of a better mechanism is a beautiful game to indicate that the headers to be used already have a compiled version and do not need to compile them again. You put this line and the compiler knows you can use the precompiled ones.

Headers are codes that are required for use of libraries containing structures, macros, and function signatures. They are included in your code and everything is compiled. It takes time to do this because it usually has several of them and some are quite large. But in general they are not changed and compiling them every time you compile your code is a waste.

You can disable this in Visual Studio, but the build will slow down.

    
20.05.2017 / 03:29
6

By default Stdafx.h is a precompiled header .

Precompiled (once compiled you do not have to compile it again). Pre-compiled header stdafx.h is basically used in Microsoft Visual Studio to allow the compiler to know the files that are compiled and there is no need to compile it from zero.

For example: If you are including the Windows header files below Code:

#include <windows.h>
#include <tchar.h>

int main() {  //your code return 0; }

The compiler will always compile these header files from scratch. But if you include #include "stdafx.h" before this includes, then the compiler will find the compiled header files of stdafx.h and not compiled from zero. But if the compiler does not find any compiled header files from stdafx.h , then it compiles the files first and then stores its compiled version in stdafx.h >. So it can be used for compilation next time.

Code:

#include "stdafx.h"
#include <windows.h>
#include <tchar.h>

int main() { //your code  return 0; }

What are its benefits:

  
  • Reduces compile time.
  •   
  • Reduce unnecessary processing.
  •   

So the conclusion:

  

Use #include "stdafx.h" where you are actually using the others   header files (such as Windows header files). Case   Otherwise, there is no need to use stdafx.h . And this does not   means that you will remove it from your project, but you can   disable this precompiled header of project settings,   by selecting the file (where you do not need this stdafx.h ) and   go to its properties and find under the "C ++ - >   Precompiled Header and select Use Precompiled Header to ... ".

That's it. I hope you have understood.

    
20.05.2017 / 04:12