C ++:避免​​重复的符号链接器错误 [英] C++: Avoiding duplicate symbol linker error

查看:87
本文介绍了C ++:避免​​重复的符号链接器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了链接器错误:

duplicate symbol __ZN5ENDF64FileILNS_7MF_enumE1EE4readEv in:
    Read.cpp.o
    Material.cpp.o

其中重复的符号名称为:

where the duplicate symbol name is:

$ c++filt __ZN5ENDF64FileILNS_7MF_enumE1EE4readEv
  ENDF6::File<(ENDF6::MF_enum)1>::read()

我知道我无法在多个地方定义相同的函数-这可能会导致此链接器错误. (我已经看到了这个问题: ld:重复符号)我不认为我有read()函数在多个位置定义,但链接器(clang++)表示可以.

I know that I can't define the same function in multiple places—that's what can cause this linker error. (I've seen this question: ld: duplicate symbol) I don't think I have the read() function defined in multiple places, but the linker (clang++) says I do.

我在哪里复制read()符号?

我的代码结构如下:

//MFs.hpp
#ifndef MFS_HPP
#define MFS_HPP
enum class MF_enum {
...
}
#endif


//File.hpp
#ifndef FILE_HPP
#define FILE_HPP

#include "MFs.hpp"

// Definition of class File
template<>
class File {
...
}

// Definition of File<...>::read() function
template <>
void File<1>::read()
{
    std::cout << "Reading into MF=1"<< std::endl;
}

#endif

因为File类是模板化的,所以没有File.cpp.所有定义(和声明)都在File.hpp

There is no File.cpp because the File class is templated. All definitions (and declarations) are in File.hpp

// Material.cpp
#include "File.hpp"
...

// Material.hpp
#ifndef MATERIAL_HPP
#define MATERIAL_HPP

#include "File.hpp"
...
#endif

最后的驱动程序代码:

// Read.cpp
#include "Material.hpp"
#include "File.hpp"

int main (){
...
}

推荐答案

(完整的)模板专业化不是模板本身.如果要专门使用该函数,则只需在标头中声明它,并在单个翻译单元中提供实现,否则就可以内联定义:

(Complete) specializations of a template are not templates themselves. If you are specializing the function, then you need to either just declare it in the header and provide the implementation in a single translation unit, or else make the definition inline:

// Header [1]
template <int>
class File {
   // ...
   void open();
};
template <>
void File<1>::open(); // just declaration

// Single .cpp
template <>
void File<1>::open() { ... }

或者:

// Header [2]
template <int>
class File {
   // ...
   void open();
};
template <>
inline void File<1>::open() { ... }

这篇关于C ++:避免​​重复的符号链接器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆