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
C++ Tutorial | Learn C++ Programming C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
5 min read
Introduction to c++
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
Setting up C++ Development EnvironmentC++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Header Files in C++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 in
6 min read
Namespace in C++Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.Namespace is a feature that provides a way to group related identifiers such as variables, functions, and
6 min read
Writing First C++ Program - Hello World ExampleThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
Basics
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
Basic Input / Output in C++In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes
5 min read
Control flow statements in ProgrammingControl flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow St
15+ min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 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++ ArraysIn C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location.Arrays in C++Create an ArrayIn C++, we can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] squar
10 min read
Strings in C++In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.Creating a StringBefore using s
5 min read
Core Concepts
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
new and delete Operators in C++ For Dynamic MemoryIn C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma
6 min read
Templates in C++C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Structures, Unions and Enumerations in C++Structures, unions and enumerations (enums) are 3 user defined data types in C++. User defined data types allow us to create a data type specifically tailored for a particular purpose. It is generally created from the built-in or derived data types. Let's take a look at each of them one by one.Struc
3 min read
Exception Handling in C++In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors.The process of dealing with exceptions is known as exception handling. It allows p
11 min read
File Handling through C++ ClassesIn C++, programs run in the computerâs RAM (Random Access Memory), in which the data used by a program only exists while the program is running. Once the program terminates, all the data is automatically deleted. File handling allows us to manipulate files in the secondary memory of the computer (li
8 min read
Multithreading in C++Multithreading is a technique where a program is divided into smaller units of execution called threads. Each thread runs independently but shares resources like memory, allowing tasks to be performed simultaneously. This helps improve performance by utilizing multiple CPU cores efficiently. Multith
5 min read
C++ OOPS
Standard Template Library (STL)
Practice Problem