Chapter 3: Header Files (Header Guards)

Introduction to Header Files

Header files in C++ are used to declare the interfaces to functions and variables. They allow the separation of declaration and implementation, providing a way to share code between multiple source files.

Example of Header File and Source Files

add.h

This is a header file that contains the function prototype for the add function.

#ifndef ADD_H
#define ADD_H

int add(int x, int y); // Function prototype for add.h

#endif // ADD_H

add.cpp

This source file includes the add.h header and provides the implementation of the add function.

#include "add.h" // Insert contents of add.h at this point. Note use of double quotes here.

int add(int x, int y) {
    return x + y;
}

main.cpp

This source file includes the add.h header and uses the add function.

#include "add.h" // Insert contents of add.h at this point. Note use of double quotes here.
#include <iostream>

int main() {
    std::cout << "The sum of 3 and 4 is " << add(3, 4) << '\n';
    return 0;
}

Header Guards

Header guards are designed to ensure that the contents of a given header file are not copied more than once into any single file, in order to prevent duplicate definitions.

Using Header Guards

#ifndef HEADER_NAME
#define HEADER_NAME

// Code

#endif // HEADER_NAME

Example with Header Guards

#ifndef ADD_H
#define ADD_H

int add(int x, int y); // Function prototype for add.h

#endif // ADD_H

Alternative: #pragma once

Another way to prevent multiple inclusions is to use #pragma once. It's not officially part of the C++ standard but is supported by most modern compilers.

#pragma once

int add(int x, int y); // Function prototype for add.h

Note: While #pragma once is simpler and reduces potential mistakes in guard naming, using traditional header guards (#ifndef, #define, #endif) is more portable and safer for cross-platform development.