tags:

views:

85

answers:

1

For a school project, the class was asked to write a String class to mimic the STL string class.

I have all the code written, but the linker seems to be caught up on one of my operators.

There are three files, String.h, String.cpp, and test2.cpp

My Makefile looks like

CC=gcc
CXX=g++
CXXFLAGS+=-Wall -Wextra
LDLIBS+=-lstdc++

all:test2

test2:test2.o String.o
test2.o:test2.cpp String.h
String.o:String.cpp String.h

make outputs the following:

g++ -Wall -Wextra   -c -o test2.o test2.cpp
g++ -Wall -Wextra   -c -o String.o String.cpp
g++   test2.o String.o  -lstdc++ -o test2
ld: duplicate symbol operator==(String const&, char const*)in String.o and test2.o
collect2: ld returned 1 exit status
make: *** [test2] Error 1

This is odd, since the only place I define operator == is in String.h:

#ifndef MY_STRING_H
#define MY_STRING_H
#include <ostream>
#include <istream>

class String {
    //...
};

// ... operators ...

bool operator ==(const String& left, const char* right)
    { return left.compare_to(right)==0; }
bool operator ==(const char* left, const String& right)
    { return right.compare_to(left)==0; }
bool operator ==(const String& left, const String& right)
    { return left.compare_to(right)==0; }

// ... other comparison operators ...
#endif

test2.cpp only has a bare main method:

#include "String.h"
using namespace std;

int main() {

}

So, if I only define operator ==(const String&, const char*) in one place, why does it say I have a duplicate symbol?

+4  A: 

You provided the definitions of the operators in the header file which gets included by both String.cpp and test2.cpp.
You should move the definitions into one source file and only provide declarations in the header file.

// in String.h:
bool operator==(const String& left, const char* right);

// in String.cpp:
bool operator ==(const String& left, const char* right) {
    return left.compare_to(right)==0; 
}
Georg Fritzsche
Alternatively, make the definitions in the header file inline. The general rule is that any function definitions in a header file should be inline, and definitions in a source file should not be inline.
KeithB