如何解决链接器错误:未定义符号 - C++ [重复]

问题描述 投票:0回答:1

尝试运行代码时遇到相同的链接器错误:

ld.lld: error: undefined symbol: Serialize::Archive& Serialize::Archive::operator>><double>(double&)

main.cpp(片段):

using namespace Serialize;
Archive arc(file, Archive::Save_Archive);
    
    double test;
    std::cout<<"Enter some data: ";
    std::cin >> test;
    arc >> test;

存档.hpp:

namespace Serialize{
template<typename T>
    Archive& operator>>(T& obj); 
}

存档.cpp:

namespace Serialize{
template<typename T>
    Archive& Archive::operator>>(T& obj){};
}

我不认为我有任何命名空间问题,并且该运算符仅在 hpp 和 cpp 文件中定义和声明一次。

我尝试切换使用命名空间序列化和命名空间序列化,甚至只是这样做

Serialize::Archive arc(file, Serialize::Archive::Save_Archive);
c++ linker linker-errors
1个回答
0
投票

您遇到的链接器错误与模板化函数的使用有关。在单独的 .cpp 文件中定义模板化函数时,编译器需要在实例化点(即模板与特定数据类型一起使用时)查看函数的实现(定义)。但是,由于模板实现通常在 .cpp 文件中找到,因此编译器在编译 main.cpp 文件时可能看不到实现。

要解决此问题,您可以为要在 main.cpp 文件中使用的数据类型显式实例化模板化函数。这将确保在编译 main.cpp 期间该函数的实现可用。

具体操作方法如下:

  1. 在 Archive.hpp 中,在文件末尾添加以下行:
// Archive.hpp

namespace Serialize {
    // ... (other code)

    // Explicit instantiation of the templated operator>> for double
    template Archive& operator>><double>(Archive& arc, double& obj);
}
  1. 在Archive.cpp中,删除模板声明并提供运算符>>的实现:
// Archive.cpp

#include "Archive.hpp"

namespace Serialize {
    // Implementation of the operator>> for double
    Archive& Archive::operator>>(double& obj) {
        // Implementation code here
        return *this;
    }

    // Other implementations for different data types if needed
}

通过在 Archive.hpp 中显式实例化双精度数据类型的 operator>> 函数并在 Archive.cpp 中提供其实现,您可以确保链接器可以在链接阶段找到所需的函数定义。

© www.soinside.com 2019 - 2024. All rights reserved.