Purpose of stdafx.h [duplicate]
Asked Answered
D

4

39

What is the purpose of the file stdafx.h and what is meant by precompiled headers?

Distillation answered 4/6, 2010 at 16:33 Comment(0)
E
31

stdafx.h is a file, generated by Microsoft Visual Studio IDE wizards, that describes both standard system and project specific include files that are used frequently but hardly ever change. Compatible compilers (for example, Visual C++ 6.0 and newer) will pre-compile this file to reduce overall compile times.

Visual C++ will not compile anything before the #include "stdafx.h" in the source file, unless the compile option /Yu'stdafx.h' is unchecked (by default); it assumes all code in the source up to and including that line is already compiled.

http://en.wikipedia.org/wiki/Precompiled_header

Eward answered 4/6, 2010 at 16:34 Comment(2)
That bit about the compiler ignoring everything before the #include "stdafx.h" is very important. I've been burned by that before.Hinch
Ya, its very important to note that compiler ignores the include files before stdafx.h , i spent around half day wondering whats happened to my code which worked previosuly fine after doing small modificationsEngage
H
13

To expand on the other excellent answers:

stdafx.h is the file that includes all of the commonly used headers for a single project. This would include all of the Windows definitions, for example. Because this file includes so much stuff, the compiler gets a bit slow when processing it. By precompiling it, the compiler can skip much of the processing and reuse it over and over again; as long as none of the files included by it change, the precompiled result doesn't need to change either.

The name stdafx.h is just a convention. You could easily rename it to something else if you changed all your sources to include the new file instead.

To produce the actual precompiled header file, you need one source file in the project that has special compile flags to produce precompiled output. By convention this file is named stdafx.cpp, and if you inspect the settings for that source file you will see how it is different.

Hinch answered 4/6, 2010 at 16:50 Comment(0)
F
6

It's typically used for the name of precompiled headers. Although using that exact name is not required, just the default. I explain more about pre-compiled headers on VC++ and g++ here.

You use precompiled headers for faster compilation.

The idea is that you put any header file that will not change, and that you use in several source files inside your precompiled header. Then the compiler will not need to reprocess those headers for each compilation unit.

Fade answered 4/6, 2010 at 16:33 Comment(0)
P
2

It's a precompiled header, to reduce compilation times.

Pfeffer answered 4/6, 2010 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.