Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++ templates linking errors?

Name: Anonymous 2009-04-15 10:02

Hi /prog/

A nice question for you. I'd like to study C++ templates, and I've found something that sound strange. This is my simple code, it implements a matrix class:

Header file (matrix.h)

#ifndef __MATRIX_H__
#define __MATRIX_H__

template <typename T>
class Matrix {
    private:
        T **matrix;
        unsigned nrows;
        unsigned ncols;
    public:
        Matrix(unsigned nrows, unsigned ncols);
};

#endif /* __MATRIX_H__ */


Implementation file (matrix.cpp)

#include "matrix.h"

template <typename T>
Matrix<T>::Matrix(unsigned nrows, unsigned ncols)
{
    int i;

    matrix = new T* [ncols];
    for (i=0; i<ncols; i++)
        matrix[i] = new T;
}


[b]Main (main.cpp)[b]

#include <iostream>
using namespace std;

#include "matrix.h"

int main(int argc, char **argv)
{
    Matrix<int> x(10,20);
}


If I try compiling this stuff the compiler works well, but there's a linker error such

/tmp/ccBo2hkV.o: In function `main':
main.cpp:(.text+0x84): undefined reference to `Matrix<int>::Matrix(unsigned int, unsigned int)'
collect2: ld returned 1 exit status


Althrough this approach stinks, I've tried to include the '.cpp' file into main.cpp instead of including the '.h' file, and it works.

Can you explain me what's going on?

Name: Anonymous 2009-04-15 11:37

>>15
Put the template definitions in the header file rather than having a separate compilation unit. It's how it has to be done.

Also, you might consider using a single-dimension array so that the entire matrix is one continuous block of memory. Might make it a bit easier to pass the stuff to SSE2 instructions. You weren't going to implement matrix manipulations without SSE2, were you?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List