I'm somewhat new at C++ (I normally work in C#, but right now I'm working on a somewhat cross-platform project), so I'm not really used to all of its concepts and exactly how compiling/linking works. So, naturally, I'm not quite sure why I'm getting this error. I've researched the error a bit, and it seems a problem people commonly get when they don't link a library or declare a function in a header file but never define it outside of that. My error, oddly, is not a result of either. The exact error text is this:
"Error 1 error LNK2001: unresolved external symbol "public: __thiscall ld22::QuadNode<class ld22::DrawableObject>::QuadNode<class ld22::DrawableObject>(class sf::Rect<float>)" (??0?$QuadNode@VDrawableObject@ld22@@@ld22@@QAE@V?$Rect@M@sf@@@Z) C:\Users\Nick\Documents\Visual Studio 2010\Projects\GDCSFMLTest\GDCSFMLTest\main.obj
"
To me, it seems like it's trying to tell me that I never made an implementation of the file. However, I have. main.cpp
, the file that compiles into main.obj and gives the error, includes Quadtree.h
, which declares the function (technically, constructor) with the line QuadNode(sf::FloatRect);
, and in the file Quadtree.cpp
I include Quadtree.h
and define the constructor as follows:
template<class T>
ld22::QuadNode<T>::QuadNode(sf::FloatRect bounds)
{
Bounds = bounds;
}
Please excuse any bad coding practices and whatnot, as I said, I'm fairly new to C++ and I'm still trying to figure things out. Any help is appreciated (especially if I made a stupid or beginners error somewhere, which I kinda feel I did), and if you need more info I'd be glad to provide it.
In C++, templated classes have to be defined in header files. This is because unlike generics in C# where they keep track of the
<T>
type at runtime, a new class is actually generated by the compiler for each<T>
you use it with. The compiler has no way to actually compile a templated form of the class, and then link-in the type information. The way I see it, templates in C++ are really a form of source-code transformation that happens before the compilation stage.See this question for more information as to why: