0

So im getting unresolved external and im confused why its not linking properly

memory.cpp: https://pastebin.com/x284CFTt

memory.hpp: https://pastebin.com/9xNcVY9q

main.cpp: https://pastebin.com/hQFTmn8E

Output Window:

1>------ Build started: Project: NAME, Configuration: Release Win32 ------
1>main.cpp
1>memory.cpp
1>main.obj : error LNK2001: unresolved external symbol "public: bool __thiscall Memory::Write<int>(unsigned __int64,int)" (??$Write@H@Memory@@QAE_N_KH@Z)
1>main.obj : error LNK2001: unresolved external symbol "public: int __thiscall Memory::Read<int>(unsigned __int64)" (??$Read@H@Memory@@QAEH_K@Z)
1>D:\Desktop\Workbench\NAME\bin\x86_Release\NAME.exe : fatal error LNK1120: 2 unresolved externals
1>Done building project "NAME.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Why its giving me these errors.. Im so confused, ive done properly the class templates i think?

xXTurner
  • 61
  • 9
  • Possible duplicate of [How to define a member function template of a template class](https://stackoverflow.com/questions/11394832/how-to-define-a-template-member-function-of-a-template-class). Usually the easiest thing to do is use [#include guards](https://en.wikipedia.org/wiki/Include_guard) and put the implementation with the declaration. – Phles Oct 12 '19 at 23:48

1 Answers1

0

The compiler needs both template class/function declaration and definition to create template class/function of specific types (int in your case).

There are the following possible solutions:

  1. Add both template declaration and definition to the header file.

  2. Add explicit template instantiation for each type to template source file. In your case add the following lines to memory.cpp

template int Memory::Read(DWORD64 Address);

template bool Memory::Write(DWORD64 Address, int dataBuffer);

  1. Include template source file memory.cpp to main.cpp. However i think that's not a nice solution.
Mathias Schmid
  • 431
  • 4
  • 7
  • for solution number 2 Do i really have to make explicit template instantiation for every possible type ? – xXTurner Oct 13 '19 at 10:41
  • Also is it a good practice if i make the whole class definition in the .hpp file? – xXTurner Oct 13 '19 at 10:44
  • Yes, if you use explicit template instantiation you have to do it for each type you are using. This is why a header-only solution is good and common practice. It's more flexible and a lot of libraries using templates do it this way. – Mathias Schmid Oct 13 '19 at 23:08