2014-09-22 98 views
0

我使用EnumParserhere它编译在VC精细++,但用gcc我有这样的错误:GCC - 多重定义错误定义模板时(VC++罚款)

./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()': 

看来EnumParser<FieldType>::EnumParser()中均出现MicexGate.oTerminator.o,这是问题所在。但我不知道为什么这是一个错误,以及如何解决它。

在我的程序中,我只在.cpp文件的MicexGate static lib项目中定义了这个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; 
} 

我怎样才能解决我的问题?

+1

你是否声明了明确的特化,并在每个使用它的文件中包含该声明?如果编译器不知道它,那么它将专门化通用模板而不是专业化,导致多个定义。 – 2014-09-22 12:26:48

回答

1

我的猜测是,你还没有宣布一个标题明确的专业化,包括在每个文件使用专业化:

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

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

或者,如同任何函数一样,只要您声明它为inline以允许在多个翻译单元中定义,就可以在其中定义它。

+0

我试图移动到.h文件并添加'inline',但这没有帮助。我会尝试添加明确的声明.h文件和实现.cpp – javapowered 2014-09-22 13:42:25

+0

我试图分离:.cpp文件中的.h文件实现中的定义。由于某种原因,这在我的情况下也不起作用。 – javapowered 2014-09-22 13:55:05

+0

@javapowered:你的意思是你在'.h'文件中(如在我的回答中)和*定义*(aka impelementation)在'.cpp'文件(如你的问题)中尝试了*声明*?这应该是有效的,只要你在需要专业化的地方包含标题。如果没有,请告诉我们你的尝试(最好是一个最小的但完整的测试用例)以及出了什么问题。 – 2014-09-22 14:14:22

1

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

+1

虽然这是事实,但并不能解释OP询问的错误。 – 2014-09-22 12:15:39

+1

这是一个明确的专业化,而不是模板定义。它像一个常规函数一样受到一个定义规则的约束;所以需要在源文件中进行,或者声明为“inline”。 – 2014-09-22 12:21:20

+0

它最初是在'.h'文件中,但我有相同的编译错误。我把它移动到.cpp,希望这可以帮助,但它不会 – javapowered 2014-09-22 12:30:27