Table of contents
1.
Introduction
2.
What are the header files in C++?
3.
Syntax of C++ Header Files
4.
Why Do We Use Header Files in C++?
5.
Example
5.1.
Implementation in C++
5.2.
C++
6.
Types of Header Files in C++
6.1.
1. Standard Header Files (Pre-existing Header Files) and Their Uses
6.1.1.
Example:
6.2.
C++
6.3.
2. User-defined Header Files and Their Uses
6.3.1.
Example:
6.4.
C++
7.
How do C++ Header Files work?
8.
How to Create Your Own Header File?
8.1.
Define the Header File
8.2.
Add Include Guards
8.3.
Declare Functions and Variables
9.
Example 
9.1.
C++
10.
Why Doesn’t iostream have a .h Extension?
11.
Including C++ Header Files from Other Directories
12.
Good Practices Related to C++ Header Files
13.
Frequently Asked Questions
13.1.
Can I include C++ standard library headers in my custom header files?
13.2.
What is the best practice for header files in C++?
13.3.
Which header file in C++ is the most used?
13.4.
How many header files are in C++?
14.
Conclusion
Last Updated: Dec 10, 2024
Easy

Header Files in C++

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Header files are crucial in C++ programming as they facilitate code reuse by including pre-written code segments in your program. These files typically contain function declarations, macro definitions, and essential information accessible by other program parts. This article will explore the syntax of header files, examine various types of header files, and provide guidance on creating your own header files in C++. In this article, we will learn about modular programming which eventually improves code maintainability and scalability.

Header Files in C++

What are the header files in C++?

In C++, header files are files with the .h or .hpp extension that contain declarations of functions, classes, variables, constants, and macros. They may also include templates, inline functions, and constants definitions that are required across multiple files. Header files serve as an interface, communicating what functionalities are available from a certain module or library without exposing the underlying implementation details.

There are two main types of header files:

  1. Standard Header Files: These are provided by the C++ Standard Library and include a wide range of functionalities, from input/output operations (like iostream) to mathematical functions (cmath) and string manipulation (string). They are included in a program by using the directive #include <header_name>.
  2. User-defined Header Files: These are created by programmers to define their own classes, functions, templates, and more, according to the needs of their specific applications. User-defined headers help in structuring projects efficiently by grouping related declarations. They are included in source files with the directive #include "header_name.h".

Syntax of C++ Header Files

In C++, a header file typically ends with the .h or .hpp extension and contains declarations of functions, variables, and data types used in various programs. To include a header file in your C++ code, you use the #include directive. This directive tells the compiler to include the content of the specified header file at that point in the program. There are two ways to use the #include directive:

Angle Brackets (<>): Used for system or standard header files. For example:

#include <iostream>


This tells the compiler to look for the iostream header in the system directories.


Double Quotes (""): Used for user-defined header files. For example:

#include "myHeader.h"


This instructs the compiler to look for myHeader.h in the current directory first and then in the system directories if not found.

Why Do We Use Header Files in C++?

Header files in C++ are used for code organization and reusability. They help manage and maintain large code bases by allowing developers to separate definitions (such as function declarations) from implementations. This separation improves clarity and minimizes the risk of errors since it keeps the implementation details hidden and exposes only what is necessary for other parts of the program to function. Additionally, header files facilitate the sharing of common declarations among multiple source files, which prevents redundancy and helps ensure consistency across the codebase. For example, a single header file can contain function prototypes used in various parts of a program, which allows any changes to the function signature to be made in just one place, thus simplifying maintenance and updates.

Here is a simple example demonstrating the use of a header file:

Example

myMathFunctions.h : 
// Header file declaration
#ifndef MY_MATH_FUNCTIONS_H
#define MY_MATH_FUNCTIONS_H


// Function to add two numbers
int add(int x, int y) {
    return x + y;
}

// Function to multiply two numbers
int multiply(int x, int y) {
    return x * y;
}


#endif

Implementation in C++

  • C++

C++

#include "myMathFunctions.h"

#include <iostream>

int main() {

   int sum = add(5, 3);

   int product = multiply(4, 2);  

   std::cout << "Sum: " << sum << std::endl;

   std::cout << "Product: " << product << std::endl;

  

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

Sum: 8
Product: 8


In this example, the myMathFunctions.h header contains functions to add and multiply numbers, which are then used in the main.cpp file.

Types of Header Files in C++

C++ header files can be broadly categorized into two types: standard (pre-existing) header files and user-defined header files. Understanding the differences and uses of each type helps in better organizing and managing code in C++ projects.

1. Standard Header Files (Pre-existing Header Files) and Their Uses

Standard header files are those provided by the C++ Standard Library. These files contain definitions and implementations of classes and functions that assist in performing tasks like input/output operations, string manipulation, and mathematical computations. Here are a few commonly used standard header files:

Header FileDescriptionCommon Functions/Classes
<iostream>Includes standard input-output stream objects for input and output operations.cin, cout, cerr
<vector>Provides the vector container class for dynamic size arrays.std::vector
<string>Contains the string class and related functions for string manipulation.std::string, append(), substr(), size()
<cmath>Provides mathematical functions for various operations like trigonometry and algebra.sqrt(), sin(), cos(), pow()
<cstdlib>Provides functions for memory allocation, random number generation, and process control.malloc(), rand(), exit()
<cstring>Offers functions for manipulating C-style strings (character arrays).strcpy(), strlen(), strcat()
<iomanip>Includes manipulators for formatting input/output.setprecision(), setw(), fixed
<cerrno>Defines macros for error codes and error handling with the errno variable.errno, perror()
<ctime>Contains functions for managing time and date operations.time(), difftime(), mktime()

Example:

  • C++

C++

#include <iostream>

#include <cmath>

int main() {

   double result = sqrt(49);  // Using the cmath header for the sqrt function

   std::cout << "The square root of 49 is " << result << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

The square root of 49 is 7

2. User-defined Header Files and Their Uses

User-defined header files are created by programmers to organize and reuse their code effectively. These headers are particularly useful in large projects where functions, templates, or variables are shared across multiple files.

Example:

// File: myUtilities.h
#ifndef MY_UTILITIES_H
#define MY_UTILITIES_H
// Function to check prime number
bool isPrime(int num) {
    for(int i = 2; i <= num / 2; ++i) {
        if(num % i == 0)
            return false;
    }
    return true;
}
#endif
  • C++

C++

#include "myUtilities.h"
#include <iostream>
int main() {
   int num = 17;
   bool prime = isPrime(num);
   std::cout << num << " is prime: " << prime << std::endl;
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

17 is prime


In this example, myUtilities.h contains a function isPrime that checks if a number is prime. This function is then used in main.cpp.

How do C++ Header Files work?

In C++, header files play a critical role in organizing and managing the structure of a program. They provide the necessary declarations for functions, classes, and variables, allowing for modularity and reusability of code. Here's an explanation of how header files work:

1. Declaration vs. Definition:

  • Declaration: Header files typically contain the declarations of functions, classes, and variables. A declaration tells the compiler about the name, return type, and parameters of a function, or the structure of a class, without providing the implementation.
  • Definition: The actual code (or implementation) of the functions and classes is typically written in .cpp (C++ source) files.
     

2. Inclusion of Header Files:

  • Header files are included in the C++ program using the #include directive. This allows the program to access the functions, classes, and variables declared in the header files.
  • The inclusion of header files can be done either using angle brackets (<>) for standard library files or double quotes ("") for custom header files.
     

3. Preventing Multiple Inclusions:

To avoid multiple inclusions of the same header file, C++ uses include guards. These are preprocessor directives that prevent the compiler from including the header file more than once in a single compilation. The standard way of defining include guards is using #ifndef, #define, and #endif.

Example:

#ifndef HEADER_FILE_NAME_H
#define HEADER_FILE_NAME_H
// Declarations
#endif

 

4. Separation of Interface and Implementation:

  • Header files often provide the interface (declarations) of a library or module, while the corresponding .cpp file contains the implementation (definitions) of the functions and methods declared in the header file.
  • This separation allows multiple files to interact with each other by including the necessary headers, without needing to know the details of how the functions or classes are implemented.
     

5. Reusability and Modularity:

  • Header files promote code reusability. Once a header file is created, it can be included in multiple source files across the project, providing a consistent interface without duplicating code.
  • By keeping code modular and separating the interface and implementation, header files help in maintaining large programs.

How to Create Your Own Header File?

Creating your own header files in C++ is a straightforward process that enhances the modularity and reusability of your code. Let’s see how we can create user-defined header file:

Define the Header File

Create a new file with a .h or .hpp extension. For example, myCustomFunctions.h.

Add Include Guards

To prevent the header file from being included multiple times, which can lead to compilation errors, use include guards. Include guards are preprocessor directives that check if a unique value (often the filename in uppercase) is defined. If not, it defines it and includes the code; otherwise, it skips including the code.

#ifndef MY_CUSTOM_FUNCTIONS_H
#define MY_CUSTOM_FUNCTIONS_H
// Your declarations and definitions go here
#endif

Declare Functions and Variables

Inside the header file, declare the functions, templates, or variables you want to reuse in other parts of your program.

// Function to check if a number is even
bool isEven(int number) {
    return number % 2 == 0;
}


Include the Header File in Your Source Files: Use the #include "filename" directive to include your header file in the C++ source files where you need the functions or variables declared in the header.

Example 

  • C++

C++

 #include "myCustomFunctions.h"

// Include guard
#ifndef MY_CUSTOM_FUNCTIONS_H
#define MY_CUSTOM_FUNCTIONS_H

// Function declaration
bool isEven(int number);

#endif

myCustomFunctions.cpp

#include "myCustomFunctions.h"

// Function definition
bool isEven(int number) {
return number % 2 == 0;
}

main.cpp

#include <iostream>
#include "myCustomFunctions.h"

int main() {
int num = 10;
std::cout << num << " is even: " << isEven(num) << std::endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

10 is even: true


In this setup, myCustomFunctions.h contains the declaration of isEven, while the definition is in myCustomFunctions.cpp. 

Why Doesn’t iostream have a .h Extension?

The reason why the <iostream> header file doesn't have a .h extension is primarily related to the evolution of the C++ Standard Library. In C++, the use of .h extensions for header files was traditionally associated with C-style headers. However, when C++ was developed, the standard library was designed to be more modern and object-oriented, distinguishing it from C.

  • C++ Standard Library Design: The decision was made to not include the .h extension for C++ standard headers to signal a clear distinction from C-style headers. For example, the C library <stdio.h> uses the .h extension, while its C++ counterpart <iostream> does not.
  • Namespace Mechanism: The C++ standard library headers often make use of the std namespace, which is a feature not present in C. The omission of the .h extension helps clarify the modern, object-oriented nature of C++.
  • Consistency: The C++ standard library follows a naming convention that avoids .h extensions for most of its headers, aligning with the modern C++ paradigm.
     

Thus, <iostream> does not need a .h extension because it is part of the C++ Standard Library, which was designed to differ from C in both its implementation and naming conventions.

Including C++ Header Files from Other Directories

In C++, header files are typically included using the #include directive. If the header file is located in a directory that is not the default or current working directory, you can specify its path. Here's how you can include header files from other directories:

  • Using Angle Brackets: For standard library headers or system-wide libraries, you use angle brackets:
  • Using Double Quotes: For custom headers, you can either place the header in the same directory as your .cpp files or specify a relative or absolute path using double quotes:
  • Specifying Include Paths: If you're compiling a program and your header files are stored in a custom directory, you can tell the compiler where to look for them using the -I flag (for GCC or Clang compilers). For example: g++ -I /path/to/headers my_program.cpp
  • Relative vs Absolute Paths: If the header files are in a subdirectory relative to the current directory, you can specify a relative path: #include "include/my_header.h"

Good Practices Related to C++ Header Files

Here are some best practices to follow when working with C++ header files:

  • Use Include Guards: Always use include guards (#ifndef, #define, #endif) in header files to prevent multiple inclusions.
  • Minimal Header Inclusion: Only include the necessary header files in your header files to minimize dependencies and reduce compilation time.
  • Forward Declarations: Use forward declarations for classes when possible, to avoid unnecessary header file inclusions.
  • Prefer .cpp Over .h for Implementations: Keep implementations (function definitions, class methods) in .cpp files rather than in header files to avoid duplication and unnecessary recompilations.
  • Avoid Circular Dependencies: Try to design your program to avoid circular dependencies between header files, as they can lead to compilation errors.
  • Namespace Usage: Use namespaces to prevent name clashes, especially when creating your own libraries.
  • Self-Contained Headers: Make sure each header file is self-contained and does not rely on the inclusion of other headers unless absolutely necessary.
  • Comment Header Files: Provide clear documentation in your header files to describe their purpose, usage, and any important details about the included functions or classes.

Frequently Asked Questions

Can I include C++ standard library headers in my custom header files?

Yes, you can include standard library headers in your custom headers. However, include only those that are necessary to keep the compilation time reasonable & dependencies clear.

What is the best practice for header files in C++?

Best practices suggest using include guards to prevent multiple inclusions and separating declarations (in header files) from definitions (in source files).

Which header file in C++ is the most used?

The `<iostream>` header is one of the most commonly used in C++ for standard input and output operations.

How many header files are in C++?

The standard C++ library includes around 140 header files, covering functionalities like input/output operations, data manipulation, and various utilities.

Conclusion

In this article, we have learned about the use and importance of header files in C++ programming. We discussed the syntax of header files, differentiated between standard and user-defined types, and saw how to create and manage your own header files effectively. Headers file is the first thing we use before creating any program, thats why we need to understand these files and their usage properly.

You can refer to our guided paths on Code360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass