main.o: In function `main':
../main.cpp:18: undefined reference to `std::vector<char, std::allocator<char> > create_list<char>(char*, unsigned int)'
This program is really simple. However, the compilations passed successfully, but the link failed. Then I move all the code into a single file, and everything works like a charm. Can anybody help me figure this out?
Solution
Yes. The answer is complicated. It has to do with how templates actually work in C++.
Long answer (reason): templates are not code that can be compiled into a binary (object). They are merely a "recipe for creating code" and code can be created only at the process of instantiation. This is also why inaccurate usage of templates may result in long compilation times and larger than needed binaries.
OTHER TIPS
You have defined your template in a separate .cpp file. Each file is compiled separately. Your create.cpp doesn't contain any running code so it is being discarded by the compiler. Later, at a linkage stage, when the linker tries to link the binary of main.cpp with create_list, it can't find it in other compiled objects thus you are getting this error. To resolve it you need to instantiate your template at least once in your create.cpp or have the implementation inside the header file.