Iinclude guards not working?

Started by
2 comments, last by DevFred 14 years, 6 months ago
Whenever I try to include this in more then one .cpp file, I always get a multiple definition error. I thought include guards were supposed to prevent that? What am I doing wrong? Also, the namespace isn't necessary. Pretty much anything I put in there will cause the same error.

#ifndef COLLISIONDETECTION_H
#define COLLISIONDETECTION_H

#include <cassert>

namespace CollisionDetect
{

    bool RectRect(double left1, double top1, double right1, double bot1, double left2, double top2, double right2, double bot2)
    {
        assert(right1>=left1);
        assert(bot1>=top1);
        assert(right2>=left2);
        assert(bot2>=top2);

        //Performs a simple collision check between two rectangles using the seperating axis theorem
        if (left1>right2) {return false;}
        if (left2>right1) {return false;}
        if (top1>bot2) {return false;}
        if (top2>bot1) {return false;}

        return true;
    }

}

#endif

I trust exceptions about as far as I can throw them.
Advertisement
Post the actual error you're getting because I suspect it's a linker error, not a compiler error. If a function is defined in a header it needs the inline keyword. If it's not really appropriate for inlining it should be in a .cpp file, not a header

-me
Quote:
I always get a multiple definition error. I thought include guards were supposed to prevent that?

That's a link error; include guards only prevent multiple passes over the header during the preprocessor phase (and thus only prevent multiple definitions within the same translation unit). Since each translation unit is compiled in isolation, however, you'll get a definition per-TU and thus a multiple-definition error when the linker tries to assemble the final product.

Kylotan's article has more details.
Quote:Original post by Storyyeller
Whenever I try to include this in more then one .cpp file, I always get a multiple definition error.

Do you define global variables in the header? That doesn't work. You need to declare them with the extern keyword, and have a definition in one cpp file only.

This topic is closed to new replies.

Advertisement