I am new to C++.
So I am creating a program which gathers then displays information about book etc. First, I want to learn little more about code I am doing but I am unfamiliar with c++ error codes.
I have created 2 classes Book and Publisher where each contains its own constructors and methods. After I tried to make my program including all classes and methods that I am given in my class diagram I came to halt when I received error saying:
1>Publisher.obj : error LNK2005: "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl getPublisherInfo(void)" (?getPublisherInfo@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) already defined in Book.obj
1>Publisher.obj : error LNK2005: "void __cdecl setAddress(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?setAddress@@YAXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) already defined in Book.obj
1>Publisher.obj : error LNK2005: "void __cdecl setCity(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?setCity@@YAXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) already defined in Book.obj
1>Publisher.obj : error LNK2005: "void __cdecl setName(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?setName@@YAXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) already defined in Book.obj
1>C:\Users\pc\Desktop\School\ITS 340\Labs\Lab 1\Lab 1\Debug\Lab 1.exe : fatal error LNK1169: one or more multiply defined symbols found
This is my Publisher.cpp file:
#include <iostream>
using namespace std;
class Publisher
{
public:
Publisher();
Publisher(string name, string address, string city);
string getPublisherInfo();
void setName(string name);
void setAddress(string address);
void setCity(string city);
private:
string name;
string address;
string city;
};
Publisher::Publisher()
{
}
Publisher::Publisher(string name, string address, string city)
{
}
string getPublisherInfo()
{
return 0;
}
void setName(string name)
{
}
void setAddress(string address)
{
}
void setCity(string city)
{
}
How can I avoid this error?
You are breaking the one definition rule. You need to declare classes and functions in header files, protect them with include guards , and only put implementations or definitions of functions and class member functions in your
.cppfiles.For example:
Foo.h:
Foo.cpp:
main.cpp
This is completely independent of OOP. You would have to do the same with free functions.