Open In App

Use of “stdafx.h” header in C++ with examples

Improve
Improve
Like Article
Like
Save
Share
Report

A header file contains the set of predefined standard library functions. The header file can be included in the program with the C preprocessing directive “#include”. All the header files have “.h” extension.

Syntax:

#include <header_file> / "header_file"

Here, 
#: A preprocessor directive
header_file: Name of the header file

The #include tells the compiler to bring header_file in the source code before executing the statements of the program.

“stdafx.h” header file

This header file is a precompiled header file. The main purpose of this header file is to reduce the compilation time. This header file is generally used in Microsoft Visual Studio.

Without stdafx.h header file:

In the below program, two header files, iostream, and cmath are used. Every time the program is compiled then for each compilation of the program, every header file is going to be compiled from scratch. Thus, the compilation time is the same in each compilation.

C++




// C++ program to implement
// the above approach
#include <cmath>
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
    cout << "GFG!";
    return 0;
}


Output

GFG!

With stdafx.h header file:

“stdafx.h” comes in handy when we want to compile a program again and again. It must be included at the top of all header files and now the first time the program is compiled then the compiled version of all the header files present in the program would be saved in “stdafx.h” file. Now, each time the program is compiled, the compiler picks up the compiled version of header files from “stdafx.h” file rather than compiling the same header files from scratch again and again. 

Example:

In this program, the “stdafx.h” header file is included. Now, once the program is compiled, cmath and iostream will be compiled from scratch and the compiled version of cmath and iostream will be saved in “stadafx.h” file. For the next time compilation, the compiler picks the compiled version of these header files from “stadafx” header file automatically.

C++




// C++ program to implement
// the above approach
 
// Importing required libraries
#include "stdafx.h"
 
#include <cmath>
#include <iostream>
 
using namespace std;
 
// Driver code
int main()
{
    cout << "GFG!";
    return 0;
}


Output: 

prog.cpp:5:20: fatal error: stdafx.h: No such file or directory
compilation terminated.

Advantages of stdafx.h header file:

  • It reduces the compilation time of those programs that are required to be compiled again and again.
  • It reduces unnecessary processing.


Last Updated : 29 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads