×

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

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Sum of all elements between k1’th and k2’th Smallest Elements

In this tutorial, we will look at how to determine sum of all given elements between two given indexes’ smallest elements. Assuming an array of integers and two numbers, k1...

2 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

C ++ Program: Alphabet Triangle and Number Triangle

Alphabet Triangle and Number Triangle An alphabet triangle is a triangle that typically looks like a pyramid or other triangles like an isosceles triangle, a right-angled triangle consisting of similar or...

4 minutes read.

Pointer to Object in C++

What is a pointer? A pointer in C++ is used to point the variable by storing the address of the variable. In C++, to print the address of the variable, we...

4 minutes read.

Armstrong Number using While Loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

4 minutes read.

Two dimension array

C++ Two dimension (2D) Array Two dimension (2D) array is an array of arrays. It is represented in the form of row and column. The elements of 2D array are accessed through the...

2 minutes read.

C++ Exception Handling

Exception is an unexpected problem that occurs at program run time. This problem might include condition such as division by zero, running out of memory space, array out of bonds, etc....

2 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 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.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.