C++ offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the ".h" extension unlike in C, Where all the header files must necessarily end with the ".h" extension. Header files in C++ are basically used to declare an interface of a module or any library.
A header file contains the following:
- Function definitions
- Data type definitions
- Macros
It offers the above features by importing them into the program with the help of a preprocessor directive "#include". These preprocessor directives are used to instruct the compiler that these files need to be processed before compilation. In C++ program has the header file which stands for input and output stream used to take input with the help of "cin" and "cout" respectively.
Syntax of Header Files in C++
#include <filename.h> // for files already available in system/default directory
or
#include "filename.h" // for files in same directory as source file
We can include header files in our program by using one of the above two syntaxes whether it is the pre-defined or user-defined header file. The "#include" preprocessor is responsible for directing the compiler that the header file needs to be processed before compilation and includes all the necessary data types and function definitions.
Example
The below example illustrates the inclusion of header files in a C++ program.
C++
// C++ program to demonstrate the inclusion of header file.
#include <cmath> // Including the standard header file for math operations
#include <iostream>
using namespace std;
int main()
{
// Using functions from the included header file
// (<cmath>)
int sqrt_res = sqrt(25);
int pow_res = pow(2, 3);
// Displaying the results
cout << "Square root of 25 is: " << sqrt_res << endl;
cout << "2^3 (2 raised to the power of 3) is: "
<< pow_res << endl;
return 0;
}
OutputSquare root of 25 is: 5
2^3 (2 raised to the power of 3) is: 8
Note We can't include the same header file twice in any program.
Types of Header Files in C++
There are two types of header files in C++:
- Standard Header Files/Pre-existing header files
- User-defined header files
1. Standard Header Files/Pre-existing header files and their Uses
These are the files that are already available in the C++ compiler we just need to import them. Standard header files are part of the C++ Standard Library and provide commonly used functionalities. They contains the declarations for standard functions, constants, and classes.
Some commonly used standard header files are:
|
It contains declarations for input and output operations using streams, such as std::cout , std::cin , and std::endl
|
It is used to perform mathematical operations like sqrt(), log2(), pow(), etc.
|
Declares functions involving memory allocation and system-related functions, such as malloc() , exit() , and rand()
|
It is used to perform various functionalities related to string manipulation like strlen(), strcmp(), strcpy(), size(), etc.
|
It is used to work with container class for dynamic arrays (vectors) functions like begin() , end().
|
Provides the std::string class and functions for string manipulation
|
It is used to access set() and setprecision() function to limit the decimal places in variables.
|
It is used to perform error handling operations like errno(), strerror(), perror(), etc.
|
It is used to perform functions related to date() and time() like setdate() and getdate(). It is also used to modify the system date and get the CPU time respectively.
|
Example
The below program demonstrates the use of Standard header files.
C++
// C++ program to demonstrate Standard header files
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
// using <iostream>
cout << "Hello, Geek!" << endl;
// using <cmath>
double squareRoot = sqrt(25);
cout << "Square root of 25 is: " << squareRoot << endl;
// using<cstdlib>
int randomNum = rand() % 100; // Generate a random
// number between 0 and 99
cout << "Random number is : " << randomNum << endl;
// using <cstring>
char mystr1[] = "Hello";
char mystr2[] = " World";
strcat(mystr1, mystr2);
cout << "string after concatenation: " << mystr1
<< endl;
// using <vector>
vector<int> numbers = { 1, 2, 3, 4, 5 };
cout << "Vector elements are: ";
for (const auto& num : numbers) {
cout << num << " ";
}
cout << endl;
// using <string>
string greeting = "Hello, ";
string name = "Programmer";
string fullGreeting = greeting + name;
cout << "Greeting message: " << fullGreeting << endl;
return 0;
}
OutputHello, Geek!
Square root of 25 is: 5
Random number is : 83
string after concatenation: Hello World
Vector elements are: 1 2 3 4 5
Greeting message: Hello, Programmer
2. User-defined header files and their Uses
These files are defined by the user and can be imported using #include" ". These are mainly used to encapsulate our own functions, classes, or declarations so that we can organize our code and reuse our code by separating it in different files.
Example
C++
#include <graphics.h>
int main()
{
initgraph(); // Initializing graphics system
circle(320, 240, 50); // Drawing a circle
delay(2000); // take Pause for 2 seconds
closegraph(); // Closing graphics system
return 0;
}
Note The above code is specific to certain compilers and environments like Turbo C++ on MS-DOS only.
How to create your own Header File?
Instead of writing a large and complex code, we can create your own header files and include them in our program to use it whenever we want. It enhances code functionality and readability. Below are the steps to create our own header file:
- step1: Write your own C++ code and save that file with ".h" extension. Below is the illustration of header file:
C++
// Function to find the sum of two
// numbers passed
int sumOfTwoNumbers(int a, int b) { return (a + b); }
- step2: Include your header file with "#include" in your C++ program as shown below:
C++
// C++ program to find the sum of two
// numbers using function declared in
// header file
#include "iostream"
// Including header file
#include "sum.h"
using namespace std;
int main()
{
// Given two numbers
int a = 13, b = 22;
// Function declared in header
// file to find the sum
cout << "Sum is: " << sumOfTwoNumbers(a, b) << endl;
}
Output
Sum is: 35
Similar Reads
clocale header file in C++
clocale: This header file contains declaration of a set of functions and a type for internationalization support tasks. It supports date format or country specific currency symbols. For example, date/time formatting, monetary formatting and many more. Methods in clocale header: localeconv(): This fu
2 min read
C++23 <print> Header
C++ has long been a powerful language, known for its versatility and performance. With each new standard release, the language evolves, introducing features that enhance developer productivity and code readability. One of these additions of the C++ 23 standard is the introduction of <print> he
3 min read
C++ 11 - <cinttypes> Header
The header offers type aliases and functions for manipulating integer types with particular sizes and signedness, as a part of the C++11 standard. Its aim is to present a standard group of integer types across diverse platforms and architectures. <cinttypes> header The <cinttypes> header
2 min read
C++ 23 - <flat_map> Header
C++23 introduces a new header, <flat_map>, which revolutionizes the manner we store and retrieve key-value pairs. Traditionally, C++ developers have depended on map and unordered_map containers for associative storage. However, the flat_map container gives a singular technique by combining the
8 min read
C++ 23 - <flat_set> Header
<flat_set> is a header file that provides the implementation of the std::flat_set container class in C++, which is a sorted associative container that stores unique elements and allows for fast access, insertion, and removal of elements. The flat_set is a container similar to the set but its e
10 min read
Use of "stdafx.h" header in C++ with examples
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 directiveheade
3 min read
C++ 11 - <cstdint> Header
<cstdint> header in C++ ensures the portability of integer types with specialized width and signedness across various systems. The absence of standardization for integer types caused issues in coding and constructing portable programs before the advent of. In this article, we will explore the
3 min read
Functions in C++
A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
9 min read
C++ 20 - <numbers> Header
C++20 has a recently developed header file labeled that incorporates mathematical functions and constants. Its purpose is to provide standard library support for mathematical operations, simplifying the process for C++ programmers to incorporate mathematical functions and constants into their progra
3 min read
C++23 - <expected> Header
C++23, the next major version of the C++ programming language, brings several exciting features and enhancements. One of the significant additions in C++23 is the <expected> header, which aims to improve error handling and make code more robust and readable. In this article, we will explore th
6 min read