1

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.

0

1 Answer 1

3

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:

2
  • MSVC allows template functions to be implemented outside of the header file but this doesn't work across dll boundaries.
    – x4u
    Jan 21, 2012 at 5:05
  • Thank you! I knew it would be some sort of silly mistake of being a beginner or not reading enough. I see I was just too used to the whole "declare in a header, define in another file" concept of C++ and assumed that it was the same for all cases. As soon as StackOverflow lets me accept this as my answer I will. Jan 21, 2012 at 5:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.