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

Asked

Viewed 5,167 times

9

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

#include "stdafx.h"

How I am at the beginning of the study of language, seeing some "hello world", did not find this line in the examples.

When removing that 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?

2 answers

8

By definition "Stdafx. h" is a precompiled header.

Precompiled (once compiled it is not necessary to compile it again). Precompiled 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 scratch.

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 the stdafx. h and not compiled from scratch. But if the compiler does not find any compiled header files from stdafx. h, then first it compiles the files 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 build time.
  • Reduces the unnecessary processing.

So the conclusion:

Use #include "stdafx. h" where you’re really using others header files (such as Windows header files). Case otherwise, no need to use stdafx. h. And that’s not means that you will remove it from your project, but you can disable this pre-compiled project settings header, by selecting the file (where you do not need this stdafx. h) and go to his properties and find under the option "C ++ -> Precompiled Header and select Use Precompiled Header to...".

That’s it. I hope you understand.

7


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

The headers are codes that are required for the 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 you usually have several of them and some are very large. Only in general they are not changed and the compilation of them every time you compile your code is a waste.

You can disable this in Visual Studio, but the compilation will be slower.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.