CS253: Software Development with C++

Spring 2020

Include Guards

Show Lecture.IncludeGuards as a slide show.

CS253 Include Guards

Multiple Inclusion

class Foo {
};

class Foo {
};
c.cc:4: error: redefinition of 'class main()::Foo'

How it happens

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?

The solution

string:

    #ifndef STRING_INCLUDED
    #define STRING_INCLUDED
    class string {
        …
    };
    #endif /* STRING_INCLUDED */

Non-standard solutions