Sobes.tech
Junior — Middle

How can you prevent multiple inclusion of the same header file during compilation?

sobes.tech AI

Answer from AI

To prevent multiple inclusions of the same header file in C/C++, include guards or the #pragma once directive are used.

Include guards look like this:

#ifndef HEADER_FILE_NAME_H
#define HEADER_FILE_NAME_H

// header file contents

#endif // HEADER_FILE_NAME_H

On the first inclusion, the macro HEADER_FILE_NAME_H is not defined, so the contents are included and the macro is defined. On subsequent inclusions, the #ifndef condition is false, and the contents are skipped.

Alternatively, you can use:

#pragma once

This directive tells the compiler to include the file only once. It is simpler but not part of the C++ standard, although it is supported by most modern compilers.