views:

233

answers:

1

I've just started with C++, and maybe there's something that I'm doing wrong here, but I'm at a loss. When I try to build the solution, I get 4 LNK2005 errors like this one:

error LNK2005: "public: double __thiscall Point::GetX(void)const " (?GetX@Point@@QBENXZ) already defined in CppSandbox.obj

(there's one for each get/set method, and they all allegedly occur in Point.obj)

And then finally this error:

error LNK1169: one or more multiply defined symbols found

Which reportedly occurs in CppSandbox.exe. I'm not sure what causes this error - it appears to happen when I build or rebuild the solution... Really at a loss, to be honest.

The three files below are the entirety of what I added to the default VS2010 blank project (they're copied in their entirety). Thanks for any help you can offer.

Point.h

class Point
{
public:
    Point() 
    { 
        x = 0; 
        y = 0; 
    };
    Point(double xv, double yv) 
    { 
        x = xv;
        y = yv; 
    };

    double GetX() const;
    void SetX(double nval);

    double GetY() const;
    void SetY(double nval);

    bool operator==(const Point &other)
    {
        return GetX() == other.GetX() && GetY() == other.GetY();
    }

    bool operator!=(const Point &other)
    {
        return !(*this == other);
    }

private:
    double x;
    double y;
};

Point.cpp

#include "Point.h"

double Point::GetX() const
{
    return x;
}

double Point::GetY() const
{
    return y;
}

void Point::SetX(double nv)
{
    x = nv;
}

void Point::SetY(double nv)
{
    y = nv;
}

CppSandbox.cpp

// CppSandbox.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include "Point.cpp"

int main()
{
    Point p(1, 2);
    Point q(1, 2);
    Point r(2, 3);

    if (p == q) std::cout << "P == Q";
    if (q == p) std::cout << "Equality is commutative";
    if (p == r || q == r) std::cout << "Equality is broken";

    return 0;
}
+6  A: 

The problem is in CppSandbox.cpp:

#include "Point.cpp"

You are including the cpp file instead of the header file, so its contents are compiled twice and everything in it is therefore defined twice. (It's compiled once when Point.cpp is compiled, and a second time when CppSandbox.cpp is compiled.)

You should include the header file in CppSandbox.cpp:

#include "Point.h"

Your header file should also have include guards.

James McNellis
That fixed it, and I've added the include guards. Thanks for your help
ehdv