Show Lecture.IncludeGuards as a slide show.
#include
-ing a file twice can cause problems.
class Foo { }; class Foo { };
c.cc:4: error: redefinition of 'class main()::Foo'
#include
something twice?
main.cc
:
#include "foo.h" #include "bar.h"
foo.h
:
#include <string>
bar.h
:
#include <string>
Both foo.h
and bar.h
use strings, so they both #include <string>
.
However, we don’t want to have an error complaining that class string
is redefined. How do we cure this?
string
:
#ifndef STRING_INCLUDED #define STRING_INCLUDED class string { … }; #endif /* STRING_INCLUDED */
<string>
is #include
d, the symbol
STRING_INCLUDED
is not defined. Therefore the rest of the
compile-time #ifndef
(if not defined)
conditional compilation is processed.
STRING_INCLUDED
is defined.
class string
is defined.
STRING_INCLUDED
is defined, so the file does nothing.
#pragma once
.
#pragma once
.