Skip to main content

Module guards

Module guards 

Source
Expand description

Include guards: recognising that a header protects itself, and remembering what a header did to the macro table.

§Why the guard is worth detecting

A header included twice would otherwise be analysed twice, and — worse — its macros would be defined twice, so a consumer asking “where is FOO defined” would get two answers for one definition and a consumer following the second would land in the middle of a header that is only included once in reality.

Both spellings are recognised, and they behave differently in a way that matters:

  • #pragma once makes the file unconditionally visit-once. The compiler decides it by identity, and so does this.
  • #ifndef GUARD / #define GUARD ... #endif is conditional: the guard macro is defined for the rest of the translation unit, so the file is skipped only when that macro is already defined — and only by a route that went through this header. So the check is “is GUARD defined and was it defined by this header”, which is why Guard::Macro carries the name rather than a flag.

Getting that second case wrong in the obvious way — treating an #ifndef header as unconditionally visit-once — breaks the case where two headers use the same guard name by accident, which is common when projects copy each other’s headers.

Structs§

FileGuard
What analysing a header did to the macro table, so a second visit can be decided.
GuardAnalysis
What was found in one file’s directives.

Enums§

Guard
How a header protects itself against being included twice.

Functions§

analyse
Analyse a parsed file’s guards.
analyse_guards
Recognise a file’s guard and collect the macros it defines.
declares_something_before_tokens
Is there code before offset — for a caller holding tokens rather than a tree?
detect_guard
Recognise a file’s guard, given its directives in source order.
detect_guard_from_tokens
detect_guard for a caller with no tree — the directive summary, which is a file’s #includes and #defines read without a parse (see FileIndexer::directive_summary).
has_a_macro_guard_from_tokens
has_a_macro_guard for a caller with no tree — see detect_guard_from_tokens.