C++:避免​​重复符号链接(symbolic link)器错误

标签 c++ linker clang

我收到链接器错误:

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

其中重复的符号名称是:

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

我知道我不能在多个地方定义同一个函数——这就是导致这个链接器错误的原因。 (我看过这个问题:ld: duplicate symbol)我不认为我在多个地方定义了 read() 函数,但是链接器 (clang++) 说我愿意。

我在哪里复制 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.cpp 因为 File 类是模板化的。所有定义(和声明)都在 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 (){
...
}

最佳答案

(完整)模板的特化本身不是模板。如果您正在专门化该功能,那么您需要在 header 中声明它并在单个翻译单元中提供实现,或者使定义内联:

// 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++:避免​​重复符号链接(symbolic link)器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23366776/

相关文章:

c++ - 如果我在 init 之外定义,如何在 ccTouchEnded 中删除子项

c++ - 包裹在协程中的 boost asio 计时器导致 clang-5.0 上的 SEGFAULT

c++ - 为什么不能在 C++ 类中重新定义类型名称?

c++ - 单程搜索和替换

c++ - error LNK2019: 未解析的外部符号“public: __thiscall Server::Server(class boost::asio::io_service &)

linux - 由于对gcry- *符号的许多 undefined reference ,因此无法链接git2-rs

ios - 将使用 Clang 构建的库添加到使用 GCC 构建的 iOS 应用程序时出现链接错误

与 stdarg 相关的 clang 错误?

c++ - 在 clang 中使用别名模板时,有没有办法缩短模板化类名?

c++ - this.attribute 应该是 this->attribute 是什么意思