We brush our teeth every day.
But do we make the toothpaste?
Someone already made the toothpaste which we are directly using.
Similar is the purpose of a header file.
Header files are files containing functions, variables, data-type definitions and constants that can be used within the programs.
We use a preprocessor directive #include to include header files in C++.
The preprocessor are the directives which tell the compiler to pre-process the specified entity before the compilation begins.
#include followed by the name of header file enclosed within <>.
Until now we have used cout a lot.
Can you guess where it comes from?
It is already defined in some header file, that’s why we can use it directly.
cout is defined in iostream header file. And, cin is also defined in the same header file.
So, to use cout and cin we must first include iostream header file.
These header files are processed before the program is compiled.
So, we have all the resources available before we use them in the program.
Fun fact, we can also write our own header files.
Header files are always included globally.
Exploring different header files in C++
There are tons of header files in C++ specifically written for different purposes.
Let’s explore few of them.
iostream is a header file which contains definitions of input/output operations.
So, cin which is used to take input and cout which is used for output are declared in iostream header file.
C++ also provides ways to perform string operations.
String function strcmp() is used to compare two strings and strcat() is used to join two strings.
These all functions are declared in string header file.
iomanip is another header file in C.
iomanip header file contains functions to control the format of input and output. It contains functions which are used to manipulate the input/output.
cmath is a header file which contains mathematical functions which can be directly used to perform numerous operations.
It contains functions to find the square root of a number, log of the number, compute the absolute value of a number, perform trigonometric operations and what not.
Everything you need.
There’s another interesting header file which is ctime.
ctime header file contains functions to perform operations on “time”.
We can return the current time, find out the difference between times, perform conversions between different time formats, etc.
Header files make our life easy.
I wonder how time-consuming it would be to write all these things from scratch and perform operations using them. Ughh!