模板构造函数中的C++链接器错误:"unresolved external symbol"

C++ linker error in template constructor: "unresolved external symbol"

本文关键字:错误 unresolved symbol external 链接 构造函数 C++      更新时间:2023-10-16

我正试图用C++编写一个模板类,但遇到了这个奇怪的链接器错误,无法找出原因,请告诉我这是怎么回事!

这是我在Visula C++2010中得到的错误消息。

1>------ Rebuild All started: Project: FlashEmulatorTemplates, Configuration: Debug Win32 ------
1>  main.cpp
1>  emulator.cpp
1>  Generating Code...
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall flash_emulator<char>::flash_emulator<char>(char const *,struct FLASH_PROPERTIES *)" (??0?$flash_emulator@D@@QAE@PBDPAUFLASH_PROPERTIES@@@Z) referenced in function _main
1>C:ProjectsFlashEmulator_templatesVSFlashEmulatorTemplatesDebugFlashEmulatorTemplates.exe : fatal error LNK1120: 1 unresolved externals
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

g++中的错误消息

main.cpp: In function âint main()â:
main.cpp:8: warning: deprecated conversion from string constant to âchar*â
/tmp/ccOJ8koe.o: In function `main':
main.cpp:(.text+0x21): undefined reference to `flash_emulator<char>::flash_emulator(char*, FLASH_PROPERTIES*)'
collect2: ld returned 1 exit status

有两个.cpp文件和一个头文件,我在下面给出了它们。

模拟器.h

#ifndef __EMULATOR_H__
#define __EMULATOR_H__
typedef struct {
    int property;
}FLASH_PROPERTIES ;
/* Flash emulation class */
template<class T>
class flash_emulator
{
private:
    /* Private data */
    int key;    
public:
    /* Constructor - Opens an existing flash by name flashName or creates one with 
       given FLASH_PROPERTIES if it doesn't exist */
    flash_emulator( const char *flashName, 
                       FLASH_PROPERTIES *properties );
    /* Constructor - Opens an existing flash by name flashName or creates one with 
       given properties given in configFIleName */
    flash_emulator<T>( char *flashName, 
                       char *configFileName );
    /* Destructor for the emulator */
    ~flash_emulator(){
    }
};
#endif  /* End of __EMULATOR_H__  */

模拟器.cpp

#include <Windows.h>
#include "emulator.h"
using namespace std;

template<class T>flash_emulator<T>::flash_emulator( const char *flashName, 
                                                    FLASH_PROPERTIES *properties ) 
{
    return;
}
template<class T>flash_emulator<T>::flash_emulator(char *flashName,
                                char *configFileName)
{
    return;
}

main.cpp

#include <Windows.h>
#include "emulator.h"
int main()
{
    FLASH_PROPERTIES properties = {0};
    flash_emulator<char> myEmulator("C:newEMu.flash", &properties);
    return 0;
}

您必须在可见标头中定义模板函数。

移动的定义

template<class T> flash_emulator<T>::flash_emulator( const char *flashName, 
                                   FLASH_PROPERTIES *properties )

template<class T> flash_emulator<T>::flash_emulator(char *flashName,
                            char *configFileName)

从emulator.cpp到emulator.h。