我正在使用 EnumParser
来自 here它在 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()':
好像EnumParser<FieldType>::EnumParser()
出现在两个MicexGate.o
和 Terminator.o
这就是问题所在。但我不知道为什么这是一个错误以及如何解决它。
在我的程序中,我只在 .cpp
中定义了一次 EnumParser文件在 MicexGate
静态库项目。 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;
}
我该如何解决我的问题?
最佳答案
我的猜测是您没有在 header 中声明显式特化,包含在每个使用特化的文件中:
template<> EnumParser<FieldType>::EnumParser();
如果没有这个声明,编译器就不知道显式特化的存在,因此如果需要的话,将从通用模板中实例化一个隐式特化。您现在有两个定义,(希望如此)导致链接错误。
或者,与任何函数一样,您可以在 header 中定义它,只要您声明它inline
以允许在多个翻译单元中定义。
关于c++ - gcc - 定义模板时出现多重定义错误(vc++ 正常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25973806/