Understanding C++ Header Files

Understanding C++ Header Files

6 mins read410 Views Comment
Updated on Feb 7, 2023 18:01 IST

In this article we will understand the concept of C++ header files. We have covered types of C++ header files and its related concepts. Let’s understand.

2023_02_C-Header-Files.jpg

Every C++ program needs at least one header file to be meaningful. For example, most C++ programs need the cin object to take input from the user and much other pre-written code, which helps to make programming easier, so to use such functionalities, you need a header file. 

Another use case of header files is that when a program grows larger and has many files, it becomes tedious to define every function repeatedly. So instead of this, we can define functions in separate files(keeping the similar type of functions in one file) and import them to any other file when required. 

Must Check: C++ Online Courses &Certification

This tutorial will discuss header files in C++, their contents, and their types, including the functions and variables they contain. We will be covering the following sections: 

Introduction to C++ Header Files

Also, Read: OOPs concepts in C++

Header files in C++ consist of functions and data types definitions, which can be included in a C++ program using the #include preprocessor directive. This directive instructs the compiler to process the header files before compilation.  

Check out- Constructors in C++ and its Types

Contents of a Header File 

A C++ header file typically contains the following: 

Function Declarations 

The header file may include predefined functions that can be utilized by including the header file in the program. For example is the math’s pow(a,b) function.h header file takes two arguments, a and b, and returns a^b. 

Data Type Declarations 

Header files may also declare commonly used data types, allowing them to be used in the program without defining them repeatedly. For instance, time_t is an arithmetic data type used to represent time. 

Macros 

A macro is a code fragment that is replaced by its value. They are used to avoid having to repeatedly type out long code snippets that are used frequently in a program. Macros are defined using the #define directive, and whenever the compiler encounters a macro, it substitutes it with its value. 

Classes 

Header files also include pre-defined classes which offer numerous useful features, simplifying programming. For instance, the C++ string class stores character sequences and is dynamic. 

Must check : Classes and Objects in C++

Types of C++ Header Files 

C++ has two types of header files: 

Standard Header Files 

These are header files already available in C++ and can be utilized by including them in the program. They are typically included using angle brackets; for example, #include<iostream>. 

User-defined Header Files 

These are header files created by the programmer and can be included in the program using double quotes; for example, #include “myheader.h”. 

Creating a Header File in C++

  • Choose a name for your header file, and make sure it has a .h extension, for example, myheader.h. 
  • Open a text editor or an IDE of your choice and create a new file with the chosen name. 
  • Write the declarations for the functions, classes, or data types you want to include in your header file. These declarations are usually in the form of prototypes, meaning that you need to specify the function name, return type, and arguments without defining the actual implementation of the function. 
  • Wrap the declarations in an #ifndef preprocessor directive to ensure that the contents of the header file are only processed once by the compiler.  
 
#ifndef MYHEADER_H
#define MYHEADER_H
// declarations go here
#endif
Copy code
  • Save the file with the .h extension in a directory accessible to your C++ programs. 
  • To use the header file in a C++ program, include it using the #include directive. 

For example: 

 
#include "myheader.h"
Copy code
  • Compile and run your program as usual. The functions, classes, and data types declared in the header file can be used in the program just like any other functions, classes, or data types. 

Note: It’s a good practice to include only the declarations in header files and keep the definitions and implementations in separate source files. This makes it easier to maintain and update your code as your program grows. 

Read More: Difference between C and C++ 

How C++ Header Files Work? 

To include a header file in a C++ program, two elements are crucial:  

  • The preprocessor directive #include  
  • The header file name <filename.h>  

The #include directive instructs the compiler to process the specified header file before compiling the program, incorporating all of its functions and data members. This is how header files are utilized in C++. 

Standard Header Files in C++

The following table describes the standard header files in C++ and which library they belong to: 

Library  Header File  Functionality 
Input/output  <iostream>  Takes input and displays output from the console using cin and cout 
Input/output  <fstream>  Used to create, write, and read information from files 
Numerics  <cmath.h>  Performs common mathematical operations 
Numerics  <complex.h>  Deals with complex number operations 
Algorithms  <algorithm>  Operates on C++ containers 
Containers  <vector>  Dynamic arrays 
Containers  <deque>  Double-ended queues for inserting and deleting elements from both ends 
Containers  <set>  Stores unique elements in a specific order 
Containers  <map>  Stores key-value pairs and unique keys 
Containers  <unordered_set>  Stores unique elements using hash tables 
Containers  <unordered_map>  Stores key-value pairs using hash tables 
Containers  <stack>  Stores values in a LIFO (last in, first out) manner 
Containers  <queue>  Stores values in a FIFO (first in, first out) manner 
Strings  <string>  Performs operations on strings 
Strings  <ctype.h>  Contains functions to handle characters 

Ways to Include Header Files in a C++ Program

There are two methods to include header files in a C++ program: 

Angle Brackets  

This method includes pre-existing header files, and the compiler searches for these files in the directories specified in the include directive. The header file is not searched in the current directory where the source code is present. This method uses angle brackets and the preprocessor directive “#include.” 

Example:  

 
#include<iostream>
Copy code

Double Quotes 

This method includes user-defined header files, and the compiler first searches for the header file in the current directory where the source code is present. If not found, it searches in the directories specified by the include directive. This method uses double quotes and the preprocessor directive “#include.” 

Example:  

 
#include "my_file.h"
Copy code
What is Static Data Member in C++
What is Static Data Member in C++
In C++, a static data member is a class variable that is shared by all objects of the class, rather than being unique to each object.
What is Static Data Member in C++
What is Static Data Member in C++
In C++, a static data member is a class variable that is shared by all objects of the class, rather than being unique to each object.
Operator Overloading in C++
Operator Overloading in C++
In C++, you can alter the way operators work for user-defined types like objects and structures. This is known as operator overloading. It is one of the best features used to...read more

Example of a Header File in a C++

Here’s a sample header file in C++: 

 
#ifndef SAMPLE_H
#define SAMPLE_H
#include<iostream>
class Sample {
public:
int num;
Sample();
~Sample();
void setNum(int x);
int getNum();
};
#endif
Copy code

This is a header file for a simple class named Sample with a single integer member variable num and several member functions, including a default constructor, a destructor, a setter function setNum, and a getter function getNum. The header file uses preprocessor directives to ensure that it can be safely included multiple times in a single program without causing any issues. 

Also Read: Top C++ Interview Questions and Answers

Endnotes 

In conclusion, header files play a crucial role in C++ programming by providing pre-defined classes, functions, and data members. C++ has a vast library of header files, making it easier for developers to perform various tasks such as input-output operations, mathematical operations, string manipulation, and algorithms. With the help of this, developers can write clean, efficient, and reusable code, making C++ a powerful and versatile programming language. 

This article helped you grasp the concept of header files in C++. Explore our C++ articles to learn more about the language and consolidate your knowledge of the fundamentals. 

Contributed By: Prerna Singh

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio