Header Files in C++

  • Last updated Apr 25, 2024

When it comes to programming in C++, understanding header files is important. Header files allow you to reuse functions, and make your code more maintainable. In this tutorial, you will learn what header files are, how to create and use them, and why they are vital in C++ development.

A header file is a file that contains a set of predefined functions, which we can import by using the preprocessor directive #include. The preprocessor directive tells the compiler that the header file needs to be processed before the compilation.

Header files are declared at the top of the program. Every C++ program needs a header file to run the program. Header files are used to reduce the complexity and number of lines of code, we don’t have to write code for every thing.

A header file in C++ may contain:

  • Function definitions
  • Data type definitions
  • Macros
Function Definitions

Header files contain a the set of predefined functions that can be used by simply including the header file in our program. For example, pow(x, y) function defined in the cmath header file that can be imported in a program to find the power of any integer value.

Example:

#include <iostream>
#include <cmath>
using namespace std;

int main() {
  cout << pow(6, 2);
  return 0;
}

In this example, we define two C++ header files that are part of the C++ Standard Library, providing access to various functions, classes, and objects:

  1. <iostream>: This provides input and output stream functionality and allows you to use the cout object, which is used in the code to output data to the console.
  2. <cmath>: This provides mathematical functions. In this code, we use the pow() function from <cmath> to calculate 6 raised to the power of 2.

The output of the above code is as follows:

36
Data Type Definition

Header files also have some data type definitions which are frequently used in the program. For example, int is an integer data type used to represent an integer number with no fractional part.

Example:

// Integer data type definition
int age = 28;

// Floating-point data types definition
float temperature = 98.6;
double pi = 3.14159265359;

// Character data type definition
char grade = 'A';

// Boolean data type definition
bool isStudent = true;
Macros

Macro is a piece of code that gets replaced by the value of the macro. Macros are defined by the #define directive. When the compiler sees the macros in the program, it replaces the value with the value contained in macros.

Example:

#include <iostream>

using namespace std;

// Define a simple constant using a macro
#define MAX_VALUE 200

// Define a macro function
#define SQUARE(x) ((x) * (x))

int main() {
    int number = 10;

    // Use the MAX_VALUE macro
    if (number > MAX_VALUE) {
        cout << "Number exceeds the maximum value." << endl;
    }

    // Use the SQUARE macro function
    int squared = SQUARE(number);
    cout << "The square of " << number << " is " << squared << endl;

    return 0;
}

In this example, we define two macros:

  1. MAX_VALUE: This is a simple constant macro. It defines the maximum value as 200. You can use it like a constant variable throughout your program.
  2. SQUARE(x): This is a macro function. It takes an argument x and returns the square of x. The macro function is defined using #define, and it's essentially a text replacement. Be cautious with macro functions, as they don't perform type-checking, and incorrect usage can lead to unexpected behavior.
Types of Header Files

There are of 2 types of header file:

  1. Pre-existing Header Files
  2. User-defined Header Files
Pre-existing Header Files

These header files are already available in C++ standard library compiler; you just need to import them. They are generally included in the program with the angular brackets.

Example:

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <unordered_map>
User-defined Header Files

These header files are defined by the user and can be included in the program using double quotes (" "). A user-defined header file has a ".h" extension. User-defined header files typically contain declarations of functions, variables, and constants, instead of the actual implementation of these elements. They serve as blueprints for your code, providing necessary information to the compiler without specifying the details of how each function or variable works.

Example:

#include "filename.h"
Creating a User-defined Header File

To create and use a user-defined header file, follow these steps:

  1. Create a file with ".h" extension (e.g., calc.h).
  2. Copy and save the code below to the file you just created with a ".h" extension:
  3. int add(int a, int b)
    {
        return (a + b);
    }
  4. Include the header file you created in your other program files using #include as shown below:
  5. #include <iostream>
    #include "calc.h" //Including user-define header file
    
    using namespace std;
    
     int main()
    {
       int a = 9, b = 19;
       cout << "Sum is " << add(a, b);
    }

    The output of the above code is as follows:

    Sum is 28
Why use Header Files?
  • Modularity: Header files allow you to break your code into smaller, manageable pieces. Each header file can represent a module or a specific part of your program.
  • Reusability: By separating declarations from implementations, you can reuse functions and variables across multiple source files. This promotes code reusability and reduces redundancy.
  • Readability: Header files enhance code readability by providing a clear interface to other developers. They serve as documentation for the public functions and variables in your code.
  • Maintenance: When changes are made to a function's implementation in a source file, other source files using the same function don't need to be updated as long as the function's declaration in the header file remains consistent.
How do Header Files Work?

When you include a header file, like #include<cmath> in the program, it tells the compiler that it possesses this function and functionality, and the compiler replaces the <cmath> with its actual functionality. For instance, we can import the cmath header file into the program and use the round() function if we need a function to remove decimal values from a floating number. In this manner, we avoid having to create our own code in order to eliminate decimal numbers from a floating value.

Example:

#include <iostream>
#include <cmath>

using namespace std;

int main() {
  cout << round(234.3423);
  return 0;
}

Output:

234