I am going through Implementation defined behavior control
and there is the following text in relation to #pragma once
:
Unlike header guards, this pragma makes it impossible to erroneously use the same macro name in more than one file.
I am not sure what this implies. Can someone explain?
TIA
Example:
// src/featureA/thingy.h
#ifndef HEADER_GUARD_FOR_THINGY
#define HEADER_GUARD_FOR_THINGY
struct foo{};
#endif
// src/featureB/thingy.h
#ifndef HEADER_GUARD_FOR_THINGY
#define HEADER_GUARD_FOR_THINGY
struct bar{};
#endif
// src/file.cpp
#include "featureA/thingy.h"
#include "featureB/thingy.h" // oops, this file is removed by header guard
foo f;
bar b;
Header guard macros require meticulous effort to keep them unique. #pragma once
does that automatically.
In fairness and for completeness, let me mention the drawback (also in the linked page): #pragma once
does not recognize the same file if it is included from multiple paths. This may be a problem for projects with an exotic file structure. Example:
// /usr/include/lib.h
#pragma once
struct foo{};
// src/ext/lib.h
#pragma once
struct foo{};
// src/headerA.h
#pragma once
#include <lib.h>
// src/headerB.h
#pragma once
#include "ext/lib.h"
// src/file.cpp
#include "headerA.h"
#include "headerB.h" // oops, lib.h is include twice
foo f;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With