模板构造函数中的C ++链接器错误:“未解析的外部符号”

时间:2012-04-01 05:10:21

标签: c++ templates linker-errors

我正在尝试用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:\Projects\FlashEmulator_templates\VS\FlashEmulatorTemplates\Debug\FlashEmulatorTemplates.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

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

emulator.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__  */

emulator.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;
}

1 个答案:

答案 0 :(得分:7)

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

移动

的定义
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。