This article discusses the working of C++ header files.
How Does a Header File Work
A header file is an important file that generally contains functions and variables declaration. Without using the header files, you won’t be able to run C++ code.
Types of Header Files in C++
We have 2 types of header files in C++.
Standard Header Files
A standard header file includes libraries that are part of C++ ISO standard and are preinstalled in a compiler. Examples of such standard header files are iostream, fstream, vector, and more.
Non-Standard Header Files
Non-Standard header files are not included in C++ ISO standard; however, the programmer defines these header files for some specific purpose. Though some of these header files are included in compilers but in most cases, the user must manually install them. Examples of such non-standard header files include bits/stdc++.h and rapidjson/document.h.
Syntax to Use Header File in C++
In C++, the header files are declared using the following syntax:
In the above syntax, the user has to replace the “header_file” name with the header they want to declare inside the C++ program.
Like, the iostream header must be included in a C++ program since without it, you won’t be able to use the cout() or std::cout function for printing the values at the console screen.
Consider the following C++ program that uses the iostream header file.
int main()
{
std::cout << "Hello linuxhint";
return 0;
}
The iostream header file in C++ will allow users to use the std::cout function and directs the compiler to output the message onto the console. However, because this program never defined or declared std::cout, how does a compiler know what it’s?
The above query can be addressed as, in the iostream header file, std::cout was already forward declared. When we use #include <iostream>, we are asking the preprocessor to copy every line of content from the file named “iostream” into the file that is being #included.
If there was no iostream header, you would have to manually write or copy each of the declarations referring to std::cout into every file’s top that used std::cout. This would be a lot of work and would necessitate a lot of understanding about how std::cout was declared. If we added or changed the function prototype, we would have to manually update each of the forward declarations. It’s much simpler to simply add #include <iostream> in your C++ code.
Conclusion
The header file is required because the C++ compiler cannot search for symbol declarations on its own, so you must assist it by including all those declarations. In this article, we have discussed the working, syntax, and importance of header files in C++ with an example in detail.