定义模板时出现多重定义错误(vc++fine)

multiple definition error when defining template (vc++ fine)

本文关键字:定义 错误 vc++fine      更新时间:2023-10-16

我在这里使用EnumParser它在VC++中编译得很好,但使用gcc我有这样的错误:

./Terminator.o: In function `EnumParser<FieldType>::EnumParser()':
Terminator.cpp:(.text+0x960): multiple definition of `EnumParser<FieldType>::EnumParser()'
./MicexGate.o:MicexGate.cpp:(.text+0xd0): first defined here
./Terminator.o: In function `EnumParser<FieldType>::EnumParser()':
Terminator.cpp:(.text+0x960): multiple definition of `EnumParser<FieldType>::EnumParser()'
./MicexGate.o:MicexGate.cpp:(.text+0xd0): first defined here
./Terminator.o: In function `EnumParser<FieldsetName>::EnumParser()':

CCD_ 2似乎同时出现在MicexGate.oTerminator.o中,这就是问题所在。但我不知道为什么这是一个错误,以及如何修复它。

在我的程序中,我只在MicexGate静态库项目的.cpp文件中定义了一次EnumParser。Terminator依赖于MicexGate,这可能就是EnumParser最终定义两次的原因。这就是我如何定义EnumParser<FieldType>:

#include "FieldsConverter.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>
#include "ByteArrayReader.h"
#include "Utils.h"
#include "CommonsMicexBridge.h"
#include "InstrumentsStorage.h"
#include <boost/algorithm/string.hpp>
template<> EnumParser<FieldType>::EnumParser()
{
    enumMap["Char"] = Char;
    enumMap["Integer"] = Integer;
    enumMap["Long"] = Long;
    enumMap["Fixed"] = Fixed;
    enumMap["Price"] = Price;
    enumMap["Date"] = Date;
    enumMap["Time"] = Time;
}

我该如何解决我的问题?

我的猜测是,您还没有在标头中声明显式专业化,该标头包含在每个使用专业化的文件中:

template<> EnumParser<FieldType>::EnumParser();

如果没有这个声明,编译器就不知道显式专业化的存在,所以如果需要的话,会从通用模板实例化隐式专业化。您现在有两个定义,结果(希望)是一个链接错误。

或者,与任何函数一样,只要声明为inline,就可以在标头中定义它,以允许以多个翻译单元进行定义。

模板需要在头文件中,而不是.cpp文件中。