1

I hit this linker error and am having a little trouble getting past it.

o/foo/bar.cc.o: In function 'foo::bar()': bar.cc:(.text+0x728): undefined reference to 'rf<PlayerInfo> Util::getClosestToGlobal<PlayerInfo>(std::vector<rf<bats::PlayerInfo>, std::allocator<rf<PlayerInfo> > >, Eigen::Matrix<double, 3, 1, 2, 3, 1>)'

Util.h file defines:

template <class ObjectClass>
static rf<ObjectClass> getClosestToGlobal(
    std::vector<rf<ObjectClass> > objects, Eigen::Vector3d targetPosGlobal);

Util.cpp defines:

template <class ObjectClass>
rf<ObjectClass> Util::getClosestToGlobal(
    std::vector<rf<ObjectClass> > objects, Eigen::Vector3d targetPosGlobal)
{
    // ...
}

I know that my cpp file compiled successfully as it recreates the .o file as expected.

Have I provided enough information here for someone more experienced to identify the problem? If not, where else should I be looking?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 1
    possible duplicate of [Why should the implementation and the declaration of a template class be in the same header file?](http://stackoverflow.com/questions/3749099/why-should-the-implementation-and-the-declaration-of-a-template-class-be-in-the) – Bo Persson May 13 '12 at 13:37
  • @Bo, it may be a duplicate, though at the time I asked I had no idea what the problem was :) Thanks for the link. It's also pretty similar to: http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file – Drew Noakes May 13 '12 at 13:38

2 Answers2

2

Template class/method definitions should be available in the header file.

mfontanini
  • 21,410
  • 4
  • 65
  • 73
  • The information you linked to semi-contradicts the 'must' in your statement though, assuming you know the types that will be used in the template at compile time (which I do in this case.) Useful information, thanks. I'm enjoying learning C++. – Drew Noakes May 13 '12 at 13:40
  • That is not a common situation. I'll modify the "must" anyway, but the correct way to define templates is to define them in the header file, or to create another type of file(sometimes a ".ipp") which will be included at the end of your header. That is just a workaround. – mfontanini May 13 '12 at 13:45
1

You need to define your templated function in the header file in which it was declared.

chris
  • 60,560
  • 13
  • 143
  • 205
  • Is that always the case for templated functions? – Drew Noakes May 13 '12 at 13:25
  • AFAIK. C++11 added `extern templates` for this purpose, but I think they've been since removed. – chris May 13 '12 at 13:26
  • Thanks, that works. It seems that you can define template methods in cpp files if you know the template types ahead of time. See this question: http://stackoverflow.com/questions/115703/storing-c-template-function-definitions-in-a-cpp-file – Drew Noakes May 13 '12 at 13:33