From a software tester's perspective
#pragma once
is shorter than an include guard, less error prone, supported by most compilers, and some say that it compiles faster (which is not true [any longer]).
But I still suggest you go with standard #ifndef
include guards.
Why #ifndef
?
Consider a contrived class hierarchy like this where each of the classes A
, B
, and C
lives inside its own file:
a.h
#ifndef A_H
#define A_H
class A {
public:
// some virtual functions
};
#endif
b.h
#ifndef B_H
#define B_H
#include "a.h"
class B : public A {
public:
// some functions
};
#endif
c.h
#ifndef C_H
#define C_H
#include "b.h"
class C : public B {
public:
// some functions
};
#endif
Now let's assume you are writing tests for your classes and you need to simulate the behaviour of the really complex class B
. One way to do this would be to write a mock class using for example google mock and put it inside a directory mocks/b.h
. Note, that the class name hasn't changed but it's only stored inside a different directory. But what's most important is that the include guard is named exactly the same as in the original file b.h
.
mocks/b.h
#ifndef B_H
#define B_H
#include "a.h"
#include "gmock/gmock.h"
class B : public A {
public:
// some mocks functions
MOCK_METHOD0(SomeMethod, void());
};
#endif
What's the benefit?
With this approach you can mock the behaviour of class B
without touching the original class or telling C
about it. All you have to do is put the directory mocks/
in the include path of your complier.
Why can't this be done with #pragma once
?
If you would have used #pragma once
, you would get a name clash because it cannot protect you from defining the class B
twice, once the original one and once the mocked version.