C++ - LNK2019 error unresolved external symbol [template class's constructor and destructor] referenced in function _main

笑着哭i 提交于 2019-11-28 19:39:53

Why don't you follow the "Inclusion Model"? I'd recommend you follow that model. The compiler needs to have access to the entire template definition (not just the signature) in order to generate code for each instantiation of the template, so you need to move the definitions of the functions to your header.

Note: In general most C++ compilers do not easily support the separate compilation model for templates.

Furthermore you need to read this.

The linker errors are because it sees the header files for Queue.hpp, but doesn't see the definitions of the functions. This is because it is a template class, and for C++, the definitions of templates must be in the header file (there are a few other options, but that is the easiest solution). Move the defintions of the functions from Queue.cpp to Queue.hpp and it should compile.

All template code need to be accessible during compilation. Move the Queue.cpp implementation details into the header so that they are available.

If you have:

template <typename T>
void foo();

And you do:

foo<int>();

The compiler needs to generate (instantiate) that function. But it can't do that unless the function definition is visible at the point of instantiation.

This means template definitions needs to be included, in some way, in the header. (You can include the .cpp at the end of the header, or just provide the definitions inline.)

An example for solving the error lnk2019:
It have to write #include "EXAMPLE.cpp" at the end of .h file

//header file codes
#pragma once
#ifndef EXAMPLE_H
#define EXAMPLE_H

template <class T>
class EXAMPLE
{

//class members
void Fnuction1();

};


//write this
#include "EXAMPLE.cpp"


#endif
//----------------------------------------------

In the .cpp file do as following

//precompile header
#include "stdafx.h"
#pragma once
#ifndef _EXAMPLE_CPP_
#define _EXAMPLE_CPP_

template <class T> 
void EXAMPLE<T>::Fnuction1()
{
 //codes
}

#endif
//-----------------------------------------------
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!