1

I'm compiling and linking my code with g++. I created a generic TimeSpan<T> class and now I am instantiating it in TimeMachine.cpp. Here is that class:

#include <iostream>
#include "TimeSpan.h"
using namespace std;

int main() {
    TimeSpan<int> t;
    return 0;
}

When I run g++ --std=c++14 TimeMachine.cpp I get the error message:

Undefined symbols for architecture x86_64:
  "TimeSpan<int>::TimeSpan()", referenced from:
      _main in TimeMachine.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Yet in TimeSpan.h, I defined the TimeSpan() symbol. Please help.

Edit: here's TimeSpan.h:

#ifndef CSS342LAB1_TIMESPAN_H
#define CSS342LAB1_TIMESPAN_H

#include <iostream>
using namespace std;

template<class T>
class TimeSpan
{
    friend ostream& operator <<(ostream &outStream, const TimeSpan &duration);
    friend istream& operator >>(istream &inStream, TimeSpan &duration);

public:
    //
    // Constructors and destructors

    TimeSpan();
    TimeSpan(T seconds);
    TimeSpan(T minutes, T seconds);
    TimeSpan(T hours, T minutes, T seconds);
    //~TimeSpan();
    //
    //getters and setters
    int getHours() const;
    int getMinutes() const;
    int getSeconds() const;
    bool setTime(int hours, int minutes, int seconds);
    //
    // operator overload
    bool operator==(const TimeSpan &duration) const;
    bool operator!=(const TimeSpan &duration) const;

    friend ostream& operator <<(ostream &outStream, const TimeSpan &duration);
    friend istream& operator >>(istream &inStream, TimeSpan &duration);
private:
    int seconds;
    int minutes;
    int hours;
};

#endif //CSS342LAB1_TIMESPAN_H
Anthony J
  • 11
  • 2
  • Just to clear up the terminology confusion. You didn't *define* `TimeSpan()` in TimeMachine.h you *declared* it. And the point is that templates must be defined in the header file not merely declared. – john Jan 20 '19 at 07:36

0 Answers0