C++ Cannot instantiate a class from another file in main.cpp

cclasslinker

I cannot get this to work

Addr.h

#ifndef ADDR_H
#define ADDR_H

class Foo{
public:
  Foo();                  // function called the default constructor
  Foo( int a, int b );    // function called the overloaded constructor
  int Manipulate( int g, int h );

private:
  int x;
  int y;
};

#endif

Addr.cpp

#include "addr.h"


Foo::Foo(){
  x = 5;
  y = 10;
}
Foo::Foo( int a, int b ){
  x = a;
  y = b;
}

int Foo::Manipulate( int g, int h ){
  return x = h + g*x;
}

main.cpp

#include "addr.cpp"

int main(){
    Foo myTest = Foo( 20, 45 );
    while(1){}
    return 0;
}

What am i doing wrong? I get these linker errors:

error LNK2005: "public: int __thiscall Foo::Manipulate(int,int)" (?Manipulate@Foo@@QAEHHH@Z) already defined in addr.obj c:\Users\christian\documents\visual studio 2010\Projects\Console Test\Console Test\main.obj

error LNK2005: "public: __thiscall Foo::Foo(int,int)" (??0Foo@@QAE@HH@Z) already defined in addr.obj c:\Users\christian\documents\visual studio 2010\Projects\Console Test\Console Test\main.obj

error LNK2005: "public: __thiscall Foo::Foo(void)" (??0Foo@@QAE@XZ) already defined in addr.obj c:\Users\christian\documents\visual studio 2010\Projects\Console Test\Console Test\main.obj

error LNK1169: one or more multiply defined symbols found c:\users\christian\documents\visual studio 2010\Projects\Console Test\Release\Console Test.exe

I would appreciate any kind of help!!!

Best Answer

#include "addr.cpp"

You're including the .cpp file to your main.cpp, which is what causing the problem. You should include the header file instead, as:

#include "addr.h"  //add this instead, to your main.cpp

Because its the header file which is containing the definition of the class Foo.

Related Topic