Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#pragma once vs. include guards [duplicate]

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

like image 550
Vinod Avatar asked Dec 17 '22 18:12

Vinod


1 Answers

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;
like image 127
eerorika Avatar answered Jan 07 '23 05:01

eerorika