Do not see template class constructor. Why?
-
Hello all!
I've got stacked in very simple issue, need fresh eye.
I am trying to implement template class into application in separate manner - header and cpp-body in separate files and got issue:Undefined symbols for architecture x86_64: "AStack<int>::AStack()", referenced from: _main in main.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [DemoVector] Error 1
When I am using it in plain main.cpp - everything works fine:
But when I am using it in separate files - it's failing
What am I missing?
-
Issue closed. Solution found https://www.codeproject.com/Articles/48575/How-to-define-a-template-class-in-a-h-file-and-imp
-
Templates are instantiated at the place they are used, meaning that the body needs to be available to the compiler at that place. In short this means you can't define the template in .cpp if you're gonna use it outside.
That's why it works in your .cpp file - declaration and definition are in the same file where it's used. When you split it to .h and .cpp only .h file gets included in the other files so the body of the template is not available.
In short - put templates bodies in the .h file. If you want to split it a bit a common practice is to put the body in another header (often with some file name postfix or a different extension e.g. .inl) and include it at the bottom of the header where your template declaration is.
EDIT: The methods described in that link are not very good. The third one is the closest to being good, but I would strongly advise against including .cpp file in the header. Build systems usually generate rules to compile only .cpp files meaning this will result in your .cpp being parsed and compiled unnecessarily. Just give it a .h or some other extension.
-
@Chris-Kawa Got it thx. I've not been using a lot the templates last 3 years. Totally forgot it.