C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Revising #pragma once

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Mon, 23 Sep 2024 14:45:21 +0100
On Mon, Sep 23, 2024 at 11:55 AM Gašper Ažman wote:
>
> HASH DOES NOT WORK. There are reasons for this in
> this thread, but they boil down to this: you'd need to hash
> the entire reachable filesystem because #include's don't
> resolve the same way depending on where the file is accessed
> from on the filesystem.
>
> #pragma once
> #include "utils.h"
>
> You'll see that header verbatim several times for different libraries
> in a translation unit and you'll miscompile. HASH DOES NOT WORK.


Giving consideration to your above sample header file which I'll call
"monkey.hpp", let's do it the other way:

    #ifndef HPP_MONKEY
    #define HPP_MONKEY
    # include "utils.h"
    #endif

The problem here is that another library might also have a file named
"monkey.hpp" and it might also use the same macro name "HPP_MONKEY" or
"H_MONKEY" or "MONKEY_HPP". So really we want to do our inclusion
guards something like:

    #ifndef HPP_MONKEY_239875623987523075623098765
    #define HPP_MONKEY_239875623987523075623098765
    # include "utils.h"
    #endif

Stick a nice long random number in there.

Received on 2024-09-23 13:45:34