Yes, but only per translation unit. Wrap the header contents in an
include guard:
your-header.hxx
1 2 3 4 5 6
|
# if ! defined YOUR_HEADER_INCLUDED
# define YOUR_HEADER_INCLUDED
// header contents here
# endif
|
Where the macro name
YOUR_HEADER_INCLUDED
is some unique symbol.
But this solves a different problem, where the same definition is included twice in the same translation unit:
header.hxx
source.cxx
1 2
|
# include "header.hxx"
# include "header.hxx"
|
After preprocessing, the single translation unit
source.cxx would contain
1 2
|
struct A {};
struct A {};
|
Which violates the One Definition Rule.
One solution is to only include the header once, but it's often the case where the same header is included indirectly through many other header files. In these cases, it can be extremely difficult to identify and resolve the source of a multiple inclusion without tearing your hair out. So a header guard can (should) be used:
header.hxx
1 2 3 4
|
# if ! defined HEADER_HXX_INCLUDED
# define HEADER_HXX_INCLUDED
struct A {};
# endif
|
source.cxx
1 2
|
# include "header.hxx"
# include "header.hxx"
|
The translation unit (
source.cxx) is semantically equivalent to the following:
1 2 3 4 5 6 7 8
|
# if ! defined HEADER_HXX_INCLUDED
# define HEADER_HXX_INCLUDED
struct A {};
# endif
# if ! defined HEADER_HXX_INCLUDED
# define HEADER_HXX_INCLUDED
struct A {};
# endif
|
Which hopefully makes it apparent why only one definition of A{} remains after preprocessing.
While it is good practice to use include guards in every header file, this wouldn't solve your problem because each translation unit is preprocessed separately, leading to the problem illustrated in the post above.
See also:
http://en.cppreference.com/w/cpp/preprocessor/include
https://en.wikipedia.org/wiki/Include_guard