定义模板时出现多重定义错误(vc++fine)
multiple definition error when defining template (vc++ fine)
我在这里使用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.o
和Terminator.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文件中。
相关文章:
- 使用命名空间时出现多个定义错误
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 尝试调用 .h 文件中定义的变量时出现变量未定义错误
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 链接阶段出现多重定义错误
- 避免模板类中的重定义错误
- 即使我没有包含多个文件,C++中的多个定义错误
- 跨多个类的全局变量而不会出现重定义错误?
- 尝试运行 wasm 函数时出现模块未定义错误
- C++ 预期的左大括号以及重定义错误
- C++:成员的越界声明必须是纯虚函数的定义错误
- c++中数组的未定义错误
- Visual C:模板类中的自定义错误消息
- 为什么C++模板不会导致多个定义错误?
- 只有一个定义/声明时标头声明变量的多堆定义错误
- C++ 在多个其他类中使用单个类 - 编译时出现多个定义错误
- 基类未定义.错误 C2504
- Q 斯坦达项重定义错误
- 可视化C++中的结构定义错误
- VC++ C2011 重定义错误 - 未使用的头文件