2

I have a link-time problem when I include a templated and non-templated class in the same .cpp file.

I went through the C++ FAQ 35.13,35.14,35.15 and it doesn't solve the problem.

http://www.parashift.com/c++-faq-lite/separate-template-class-defn-from-decl.html

I'm using Xcode 5 with clang.

Here's the example

barfoo.h

class bar{
public:
   void barfunc();
};

template <class T>
class foo{
public:
   void foofunc();
};

Here's the cpp file:

barfoo.cpp

void bar::barfunc(){...my code...}
template <class T>
void foo<T>::foofunc() {...my code...}
//I also put a instance of template class foo in the .cpp file
template class foo<int>;
//But is still generates the link error

The error is

clang: error: linker command failed with exit code 1 (use -v to see invocation)

But when I remove the bar class, the error disappears, can anyone tell me why it generates this error?

Put the definition in the header file could solve the problem, but it may cause another problem that is code bloating, does anyone can give another solutions?

Community
  • 1
  • 1
Charles Chow
  • 1,027
  • 12
  • 26
  • 3
    The instantiation doesn't help. You can't put a definition that applies to all `T` in a different translation unit. – chris Feb 19 '14 at 21:57
  • Thank you for your fast response, so what should I do to avoid this error? – Charles Chow Feb 19 '14 at 22:00
  • 2
    If you're defining it for all `T`, it needs to go in the header or somehow otherwise be included in the header (e.g., the header including the definition's file at the bottom). – chris Feb 19 '14 at 22:01
  • 1
    In other words, put the definition of the method `foofunc` into the header as well. – Lemming Feb 19 '14 at 22:01

1 Answers1

1

I found the problem, the problem is I didn't instantiate the template class to the type I'm using in the code.

Here's the solutions to solve the template instantiate problem:

  1. Put definition in header file so the compiler will have the instance information. (disadvantage, increase the loading and compiling time)

  2. Instantiate all types that using in the code

Community
  • 1
  • 1
Charles Chow
  • 1,027
  • 12
  • 26