×

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a specific header file is included numerous times, either directly or indirectly which results error.

Let's look at one example to understand better the requirements for including guards:

Create an Animal class in program one and save it as "Animal.h". The program for the same is listed below:

// A header is created by a C++ program.
//The file is called "Animal.h."
#include <iostream>
#include <string>
usingnamespace std;
// Animal Category
class Animal {
    string name, color, type;
public:
    // The ability to accept input
    void input()
    {
        name = "Dog";
        color = "White";
    }
    // Member variables show function 
   // variables
    void display()
    {
        cout << name << " is of "
             << color << endl;
    }
};

Create a Dog class in program two and save it as Dog.h. Don't forget to include the "Animal.h" header file:

//Header file creation in C++
//referred to as Dog.h
/ /Include the "Animal.h" header file.
#include "Animal.h"
// Canine Class
class Dog {
    Animal d;
public:
    // Add input to a variable's member
   // calling a function from another
  //header file,   
 void dog_input() { d.input(); 
    // a feature that shows the member
    // variable calling a function
    // a different header file
    void dog_display() { d.display(); }
};

Create a main.cpp file in program three and place it above both header files. The program for the same is listed below:

// a C++ application to demonstrate
// comprise guards
#include "Animal.h"
#include "Dog.h"
#include <iostream>
usingnamespace std;
// Driver Number
int main()
{
    // Dog-class objects in
    // the header file "Dog.h"
    Dog a;
    // Call Member Function
    a.dog_input();
    a.dog_display();
  
    return 0;
}

Output:

Include Guards in C++

The following error occurs when the program "main.cpp" mentioned above is run:

Explanation:

This problem is caused by the fact that there are two definitions of the Animal Class in the "main.cpp" program, which is created when including Animal.h is used to build the program and define the Animal class. Now let's use include guards to fix the problem.

The C and C++ programming languages use a special construct called a #include guard, often referred to as a macro guard, header guard, or file guard, to avoid the problem of double inclusion when using the include directive.

Solution:

Regardless of how many times a file is included, include guards guarantee it that the compiler will only process it once. Pre-processor directives called have guards ensure that a file will only be included once.

  • #ifndef: It checks to see if the specified macros are present.
  • #define: It is used to define the macros using.
  • #endif: It terminates the directive #ifndef.

Example:

#define ANIMAL(Any word you like but unique to program)
#define ANIMAL(same word as used earlier)
class Animal {
};
#endif

Define the "Animal.h" header file as follows:

// ANIMALS IF DECLARED is checked.
#ifndef _ANIMALS_
//If applicable, define "ANIMALS."
//circumstances fail
#define _ANIMALS_
#include <iostream>
#include <string>
usingnamespace std;
// Animal Category
class Animal {
    string name, color, type;
public:
    // function to receive input
    // component variable
    void input()
    {
        name = "Dog";
        color = "White";
    }
    // feature that shows the
    // component variable
    void display()
    {
        cout << name << " is of"
             << color << endl;
    }
};
#endif 

Output:

Include Guards in C++

Explanation: 

Animal.h is included, and the animal class is declared when primary.cpp executes. The code continues to run smoothly despite the Animal's first line. h header is directed, and _ANIMALS_ is not defined. When the Dog. The h header file, which in turn contained Animal.h, was included, this time _ANIMALS_ was defined in the program; therefore, the first line's #ifndef condition was true, skipping to the last line's #endif. If the pre-processor has that name specified, it skips the entire file and jumps to #endif rather than processing it.


Related Topics

Advanced C++ with Boost Library

The goal of the Boost Libraries is to be widely applicable and used in a variety of applications. For instance, they can in handy when working with huge numbers whose...

4 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

std::distance() in C++

The primary function of std::distance is to facilitate the total number of elements if we have two iterators. It is defined inside the header files. It has both magnitude and...

2 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Binary Search in C++

The binary search in the C++ programming language will be discussed. By continually halves the array and then seeking specified items from a half array; binary search is a technique...

8 minutes read.

Palindrome Number Program in C++

A palindrome number is one that is the same when it is reversed. Palindrome numbers include 22, 33, 44, 55, 66, 77, 88, and 99. Algorithm for Palindrome Numbers Get the user's...

4 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

4 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

C++ Overriding

C++ Function Overriding When the base and derive class both contain the same function name and calling the function through derived object invokes derived class function called function overriding. Function overloading is...

1 minute read.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

Free vs delete() in C++

Free vs delete() in C++ In this section, we will learn about the free() function and also create a C ++ program of the delete operator. What is free() Function in C++? In...

4 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.