c++ - gcc - 定义模板时出现多重定义错误(vc++ 正常)

标签 c++ gcc

我正在使用 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.oTerminator.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/

相关文章:

c - 如何解决 GCC 警告 "the address of XXX will never be NULL"?

c++ - 强制 std::vector 释放其内存?

c++ - 为什么 QCustomPlot 在绘制大数据时速度太慢?

c++ - 了解 void f(const T& param) 中参数的类型

c++ - NEON vector 数据类型的别名

c - 该 C 程序在其他计算机上按预期运行,但在我的计算机上表现奇怪

c++ - GCC 链接/符号名称与 C++ 和汇编程序文件的修改

android - 如何在 Android NDK Revision 11 中切换 gcc 和 clang?

c++ - 查找具有偶数值的 vector 元素

c++ - 函数 undefined reference C++