If I have all my code in a single source file, let`s say “my.cpp”, where IÂ´ve coded a templete class, like:
And the methods… then the main() function use this class and this methods, and all work fine.
The problem is when I separate the class definition and it`s methods in differents files (for example my_class.cpp & my_class.h) and the main function in other file “my.cpp”.
I compile my_class.o ok but I canÂ´t link it. The error message that the linker gives to me its and undefined reference like this:
my.cpp:26: undefined reference to `my_class::my_method(int const&)'Â´
If I don’t use templates (lets say I replace all by ‘int’ type) everything compile and I can link the objet class and the main file in a perfect way. The problem is linking against “templates” classes. What could be?
A template is like a big #define ( i’m oversimplifying ). The compiler will take the template and generate the code when needed, hence if you put some of the template code in myclass.c when my.cpp gets compile the compiler doens’t have all that i needs to generate the code.
All template definitions must be in .h / .hpp files, not .cc / .cpp files. This is one of those “so fundamental nobody bothers to mention it” problems. Deitel & Deitel skips it entirely. It is mentioned briefly in “New Language Features” of “The C++ Standard Template Library, A Tutorial and Reference,” by Nicolai M. Josuttis. Page 10 says:
Okay, so I glossed a bit in my first sentence. You can have a template definition in a .cpp file and use it IN THAT SPECIFIC .CPP FILE. You can’t link. C++ doesn’t link templates. Period. That’s one of the reasons it takes so damn long to compile C++ code compared to C. All of the C libraries you link against are already compiled. Use anything from the STL, however, and you’re compiling from scratch every time.
Also, I don’t know why he uses the word “inline.” I almost never declare my template functions “inline,” and there’s no such thing as an inline class. I suspect he means “inline” not like the keyword, but “inline” like “immediately with the declaration, rather than splitting the declaration and definition up.”
Bottom line: your templates go in .hpp files.
Sage Automation, Inc.
P.S. Despite this oversight, I still recommend Deitel & Deitel, for C++ or Java. It’s good for teaching and as a reference book. “The C++ Standard Template Library” is also an excellent reference. Also, “Effective C++,” “More Effective C++,” and “Effective STL,” all by Scott Meyers.
I believe that if you specify inline you give a hint that the code of the template must be inlined with the code that used it. Other wise the compiler might create functions that gets called each time they are used. That being said from my observerations the compiler will decide whether inline is required or not, the inline statement often won’t make a difference.