title: multiple definition of template specialization when using different objects
body: <p>When I use a specialized template in different object files, I get a "multiple definition" error when linking. The only solution I found involves using the "inline" function, but it just seems like some workaround. How do I solve that without using the "inline" keyword? If that's not possible, why?</p>
  
  <p>Here is the example code:</p>
  
  <pre><code>paulo@aeris:~/teste/cpp/redef$ cat hello.h 
  #ifndef TEMPLATE_H
  #define TEMPLATE_H
  
  #include &lt;iostream&gt;
  
  template &lt;class T&gt;
  class Hello
  {
  public:
      void print_hello(T var);
  };
  
  template &lt;class T&gt;
  void Hello&lt;T&gt;::print_hello(T var)
  {
      std::cout &lt;&lt; "Hello generic function " &lt;&lt; var &lt;&lt; "\n";
  }
  
  template &lt;&gt; //inline
  void Hello&lt;int&gt;::print_hello(int var)
  {
      std::cout &lt;&lt; "Hello specialized function " &lt;&lt; var &lt;&lt; "\n";
  }
  
  #endif
  </code></pre>
  
  <hr>
  
  <pre><code>paulo@aeris:~/teste/cpp/redef$ cat other.h 
  #include &lt;iostream&gt;
  
  void other_func();
  </code></pre>
  
  <hr>
  
  <pre><code>paulo@aeris:~/teste/cpp/redef$ cat other.c 
  #include "other.h"
  
  #include "hello.h"
  
  void other_func()
  {
      Hello&lt;char&gt; hc;
      Hello&lt;int&gt; hi;
  
      hc.print_hello('a');
      hi.print_hello(1);
  }
  </code></pre>
  
  <hr>
  
  <pre><code>paulo@aeris:~/teste/cpp/redef$ cat main.c 
  #include "hello.h"
  
  #include "other.h"
  
  int main()
  {
      Hello&lt;char&gt; hc;
      Hello&lt;int&gt; hi;
  
      hc.print_hello('a');
      hi.print_hello(1);
  
      other_func();
  
      return 0;
  }
  </code></pre>
  
  <hr>
  
  <pre><code>paulo@aeris:~/teste/cpp/redef$ cat Makefile
  all:
      g++ -c other.c -o other.o -Wall -Wextra
      g++ main.c other.o -o main -Wall -Wextra
  </code></pre>
  
  <hr>
  
  <p>Finally:</p>
  
  <pre><code>paulo@aeris:~/teste/cpp/redef$ make
  g++ -c other.c -o other.o -Wall -Wextra
  g++ main.c other.o -o main -Wall -Wextra
  other.o: In function `Hello&lt;int&gt;::print_hello(int)':
  other.c:(.text+0x0): multiple definition of `Hello&lt;int&gt;::print_hello(int)'
  /tmp/cc0dZS9l.o:main.c:(.text+0x0): first defined here
  collect2: ld returned 1 exit status
  make: ** [all] Erro 1
  </code></pre>
  
  <p>If I uncomment the "inline" inside hello.h, the code will compile and run, but that just seems like some kind of "workaround" to me: what if the specialized function is big and used many times? Will I get a big binary? Is there any other way to do this? If yes, how? If not, why?</p>
  
  <p>I tried to look for answers, but all I got was "use inline" without any further explanation.</p>
  
  <p>Thanks</p>