-1

I have 3 files - main, Array.hh, and Array.cc. When I do "g++ main.cc Array.cc", I get all kinds of linker errors, e.g.: "undefined reference to Array<<\double>>::Array(int)"

I read the other stackoverflow entries for linker errors with templates, but they are recommending to split the HH and CC files, which I have already done. So what can be the problem here?

Edit: Thanks for the replies. I had not understood the posts I had read previously. Merging the Array.cc into the Array.hh solves the problem. Closed.

main.cc:

#include "Array.hh"
#include <iostream>

int main() {
    Array<int> anArray(12);
    Array<double> adArray(12);

    for (int nCount = 0; nCount < 12; nCount++) {
        anArray[nCount] = nCount;
        adArray[nCount] = nCount + 0.5;
    }

    for (int nCount = 11; nCount >= 0; nCount--)
        std::cout << anArray[nCount] << "\t" << adArray[nCount]
        << std::endl;

    return 0;
}

Array.hh:

template <typename T>
class Array {
    private:
        int m_nLength;
        T *m_ptData;

    public:
        Array();
        Array(int nLength);
        ~Array();
        void Erase();
        T& operator[](int nIndex);
        int GetLength();
};

Array.cc

#include "Array.hh"
template <typename T>
Array<T>::Array() {
    m_nLength = 0;
    m_ptData = 0;
}

template <typename T>
Array<T>::Array(int nLength) {
    m_ptData= new T[nLength];
    m_nLength = nLength;
}

template <typename T>
Array<T>::~Array() { delete[] m_ptData; }

template <typename T>
void Array<T>::Erase() {
    delete[] m_ptData;
    m_ptData= 0;
    m_nLength = 0;
}

template <typename T>
int Array<T>::GetLength() { return m_nLength; }
R71
  • 4,283
  • 7
  • 32
  • 60
  • 3
    "I read the other stackoverflow entries for linker errors with templates, but they are recommending to split the HH and CC files" - There's no way they recommend that, that is exactly what's causing the error. – interjay Jul 03 '13 at 14:09

3 Answers3

0

Put the definitions from Array.cc into Array.hh

When a template class is used, a class is created. Array.cc does not know which classes should be created from the template, only main.cc knows that. main.cc does not know how to create the classes, because it does not know the definition of the member functions of Array, only Array.cc knows that.

Oswald
  • 31,254
  • 3
  • 43
  • 68
0

You need to #include "Array.cc"

A template can't be instantiated if its definition is not available.

This separation of definition and declaration is fine, but you must include the cc file whereever you are instatiating that template with a new type

Salgar
  • 7,687
  • 1
  • 25
  • 39
0

Recommendations you took are not very accurate. You should not separate your templates into .h and .cpp files. If you insist on putting them separate, "export" is the keyword you are looking for. For more information about "export" check here: http://www.parashift.com/c++-faq/separate-template-fn-defn-from-decl-export-keyword.html.

lgn
  • 36
  • 1