Sobes.tech
Junior

Do you know how to protect a header file from being included multiple times?

sobes.tech AI

Answer from AI

Yes, I know.

There are two main ways:

  1. Using preprocessor directives (#ifndef, #define, #endif):

    // filename.h
    #ifndef FILENAME_H
    #define FILENAME_H
    
    // Contents of the header file
    
    #endif // FILENAME_H
    

    When the file FILENAME_H is included for the first time, the macro FILENAME_H is not yet defined, so the code block between #ifndef FILENAME_H and #endif is processed by the preprocessor. Inside this block, the macro FILENAME_H is defined. On subsequent includes of this file within the same translation unit, FILENAME_H is already defined, and the code block is ignored.

  2. Using #pragma once:

    // filename.h
    #pragma once
    
    // Contents of the header file
    

    This directive is non-standard (though supported by most modern compilers) and tells the compiler to include this file only once per translation unit. The compiler tracks this automatically and prevents multiple inclusions.

Comparison:

Feature #ifndef/#define #pragma once
Standardization Part of C/C++ standard Not part of C/C++ standard
Compiler support Wide (all standard compilers) Wide (most modern)
Ease of use Requires unique macro name Simpler, no need for unique macros
Portability More portable Less portable (but widely supported)

Both approaches effectively prevent multiple inclusions, which is necessary for correct compilation and avoiding errors related to multiple entity definitions (classes, functions, variables).