Defined in header <cparse/Generator.hh>

virtual std::string generateHeaderGuard( std::string const& header ) const noexcept;

Composes a header-guard identifier from getNamespacePath() and header, in five steps:

  1. Start with getNamespacePath().
  2. If non-empty, append '/' then header; otherwise just header.
  3. Upper-case the result.
  4. Replace every non-alphanumeric with '_'.
  5. Collapse any run of consecutive underscores to a single _, then strip leading underscores.

The result is a valid identifier regardless of what characters appeared in the inputs.

Parameters

ParameterDescription
headerHeader filename or path. Typically ends in .hh / .h; the extension is preserved by upper-casing the letters and mapping the dot to _.

Return value

An all-caps identifier suitable for #ifndef / #define guards.

For a subclass whose getNamespacePath() returns "fedem::parser":

generateHeaderGuard("Cursor.hh")
// → "FEDEM_PARSER_CURSOR_HH"

Exceptions

noexcept.

Notes

The consecutive-underscore collapse handles the case where :: in the namespace path becomes __ after step 4: FEDEM::PARSER/CURSOR.HHFEDEM__PARSER_CURSOR_HHFEDEM_PARSER_CURSOR_HH. Leading-underscore strip handles a starting / if the namespace path was empty but the header started with a slash.

Example

Typical use in an emitter:

void MyGen::emitHeaderGuardOpen(std::string const& fileName)
{
    auto const guard = generateHeaderGuard(fileName);
    getStream() << "#ifndef " << guard << "\n"
                << "#define " << guard << "\n\n";
}

See also