Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of Header Files in C++
3.
Example
3.1.
Main.cpp 
3.2.
C++
4.
Types of Header Files in C++
5.
1. Standard Header Files (Pre-existing Header Files) and Their Uses
5.1.
C++
6.
2. User-defined Header Files and Their Uses
6.1.
main.cpp
7.
How to Create Your Own Header File
7.1.
Define the Header File
7.2.
Add Include Guards
7.3.
Declare Functions and Variables
8.
Example 
8.1.
C++
9.
Frequently Asked Questions
9.1.
Can I include C++ standard library headers in my custom header files?
9.2.
How do I handle circular dependencies in header files?
9.3.
Is it better to define functions inside header files or source files?
10.
Conclusion
Last Updated: Jun 9, 2024
Easy

Header Files in C++

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Header files are an essential part of C++ programming. They allow you to include pre-written code in your program, making it easier to reuse code. Header files contain function declarations, macro definitions, & other important information that can be used by other parts of the program. 

Header Files in C++

In this article, we will talk about the syntax of header files, different types of header files, & how to create your own header files in C++.

Syntax of Header Files in C++

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.

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

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

Main.cpp 

  • 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;

}

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:

  • <iostream>: Includes standard input-output stream objects like cin, cout, cerr, etc.
     
  • <vector>: Provides the vector container class that encapsulates dynamic size arrays.
     
  • <string>: Contains string class and related functions.
     
  • <cmath>: Includes functions for performing mathematical operations such as sqrt, sin, cos, etc.

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;

}

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

main.cpp

#include "myUtilities.h"
#include <iostream>
int main() {
    int num = 17;
    bool prime = isPrime(num);
    std::cout << num << " is prime: " << prime << std::endl;
    return 0;
}

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 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;
}

Output

10 is even: true


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

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.

How do I handle circular dependencies in header files?

To avoid circular dependencies, use forward declarations wherever possible & design your header files to minimize interdependencies.

Is it better to define functions inside header files or source files?

For small, inline functions, it's acceptable to define them in header files. However, for larger functions, it's best to declare them in header files & define them in source files to reduce compile time & manage code more efficiently.

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 the Coding Ninjas. 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.

Previous article
While Loop in C++
Next article
Basic C++ Programs
Live masterclass