2
votes

main.cpp

#include "test.cpp"

int main()
{

}

test.cpp

// test.cpp
#include <iostream>
using namespace std;

class Test
{
public:
    friend ostream& operator<<(ostream& out, Test& o1);
};


ostream& operator<<(ostream& out, Test& c)
{
    return out;
}

Output:
Error 1: Severity Code Description Project File Line Column Suppression State Error LNK2005 "class std::basic_ostream<char,struct std::char_traits > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits > &,class Test &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAVTest@@@Z) already defined in crops.obj Test E:\Desktop\University\Programming\C++\KPI\Test\Test\main.obj
Error 2: Severity Code Description Project File Line Column Suppression State Error LNK1169 one or more multiply defined symbols found Test E:\Desktop\University\Programming\C++\KPI\Test\Debug\Test.exe 1 1

Why I have two linkage errors? What coul d be wrong there?

1
Never include .cpp-files. How do you compile?churill
Offtopic: const is missing: ostream& operator<<(ostream& out, const Test& c)Marek R

1 Answers

4
votes

The Error message is descriptive there, you are redefining the operator. That happen because you are trying to link objects that contains the same definition. The problem here is that you are including the "test.cpp" and you are probably compiling it (and then trying to link).

You should include only files containing declarations (typically .h), you should create something like this:

//test.h
//declarations and inline methods only here
#include <iostream>
using namespace std;

class Test
{
public:
    friend ostream& operator<<(ostream& out, Test& o1);
};


ostream& operator<<(ostream& out, Test& c);
//test.cpp
//definitions here
#include "test.h"
ostream& operator<<(ostream& out, Test& c)
{
    return out;
}
//main.cpp
#include "test.h"

int main()
{

}

Then compile test.cpp, main.cpp and link the two together.