0

Possible Duplicates:
Templated function being reported as “undefined reference” during compilation
Why can templates only be implemented in the header file?

Hi, I'm having a problem with dependencies in a c++ program that only originates when I use templates. Apparently the compiler is not able to instantiate the template for a concrete type and I don't know why.

Suppose I have this library (the real program where I find this is much bigger, but I think this seems to reproduce my original problem):

//temp.cpp file
#include "temp.hpp"

template <typename a> 
void printVector(std::vector<a> xs) {
  for_each(xs.begin(), xs.end(), [](a x) {std::cout << x << " ";});
}

void printDoubVector(std::vector<double> xs) {
  for_each(xs.begin(), xs.end(), [](double x) {std::cout << x << " ";});
}

with this header file:

#include <vector>
#include <algorithm>
#include <iostream>


template <typename a> void printVector(std::vector<a> xs);
void printDoubVector(std::vector<double> xs);

And this main file:

#include "temp.hpp"

int main(){
  std::vector<double> foo(10,1);
  printVector(foo);
  std::cout << std::endl;
}

When I compile them with this makefile:

CC=g++-4.5
FLAGS = -std=gnu++0x -Wall

all: test

test: temp.o main.o
    $(CC) $(FLAGS) $^ -o $@

%.o: %.cpp
    $(CC) $(FLAGS) -c $^ -o $@

I got a undefined reference to 'void printVector<double>(std::vector<double, std::allocator<double> >)' error.

Of course, if I do printDoubVector(foo); instead of printVector(foo);, it compiles normally. If everything's in the same file, it also compiles normally. I also tried to do printVector<double>(foo); with no result. Apparently the compiler knows I want a printVector<double>, he just can't find it. :(

I don't understand this problem. I was using templates in different files before without any problems at compilation. :( Yet, it feels like something very basic that I should know at this level. :/

Community
  • 1
  • 1
Rafael S. Calsaverini
  • 13,582
  • 19
  • 75
  • 132

1 Answers1

3

The reason is described in detail here.

In short, you need to provide the full definition in the header-file, otherwise the compiler cannot instantiate the template.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • Damn... I really should know this! This is what I get by learning C++ from crappy books. :( – Rafael S. Calsaverini Jun 02 '11 at 14:08
  • 1
    @Rafael: You should have used one of [these](http://stackoverflow.com/questions/388242/). – Björn Pollex Jun 02 '11 at 14:09
  • yeah, I know... people told me [here](http://stackoverflow.com/questions/4315214/how-to-learn-to-write-idiomatic-c-code) that the book I read was really bad. I fell like I have to learn c++ from scratch again everytime I stumble in a dumb error like this. – Rafael S. Calsaverini Jun 02 '11 at 14:14