【问题标题】:Unresolved external symbol when using std::wstring使用 std::wstring 时未解析的外部符号
【发布时间】:2016-07-06 20:02:58
【问题描述】:

我声明了以下类:

#pragma once

#include <stdio.h>
#include <vector>
#include <string>

namespace util
{

class FileReader
{
public:
    FileReader();
    ~FileReader();

    bool open(const std::wstring& name);
    void close();
    bool read(std::vector<char>& buf, __int64 startFrom, int size);
    __int64 size() const;

private:
    FILE* m_file;
    std::wstring m_name;
    __int64 m_size;
};

}

及其实现:

#include "FileReader.hpp"

namespace util
{

bool FileReader::open(const std::wstring& name)
{
    if (!name.empty() && (m_name != name))
    {
        close();
        if (_wfopen_s(&m_file, name.c_str(), L"rb") == 0)
        {
            m_name = name;
            // Get the file size
            _fseeki64(m_file, 0, SEEK_END);
            m_size = _ftelli64(m_file);
            rewind(m_file);
        }
        else
        {
            m_file = NULL;
        }
    }
    return (m_file != NULL);
}
// ....
}

在一个单独的库中并像这样使用它:

文件传输.cpp

#include <util/FileReader.hpp>

// .....    

if (!m_fileReader.open(m_localFileName))   //   std::wstring m_localFileName;
{
    ::MessageBoxA(NULL, "Failed to open file", "Error", MB_ICONERROR);
    stopFileTransmission();
    return;
}

在另一个项目中。两个项目都编译成功,但是 FileTransfer.obj 链接失败:

错误 2 错误 LNK2019: 无法解析的外部符号 "public: bool __thiscall util::FileReader::open(class std::basic_string,class std::allocator > const &)" (?open@FileReader@util@@QAE_NABV?$basic_string@GU?$char_traits@G@std@@V?$allocator@G@2@@std@@@Z) 在函数中引用 __catch$?onRequestDirClicked@FileTransferWindow@@AAEXXZ$0 C:\Users\x\Documents\dev\Server\FileTransfer.obj 服务器

我记得当我使用std::string 时它正在工作,所以我认为它与std::wstring 有关。

知道可能是什么问题吗?

【问题讨论】:

  • 它不会解决您的问题,但我的第一条评论是您应该避免将 include 指令添加到您的标题中,除非标题本身使用符号。即便如此,更喜欢前向声明。
  • 我假设实现也在命名空间util?
  • 是的,bool FileReader::open的实现在util命名空间内
  • 您确定将原型更改为 wstring 后包含 filereader 的文件已重建吗?如果不是,文件中的函数仍然是filereader (string) 而不是filereader (wstring),这会导致这个错误。
  • 是的,我确实已经清理并重建了 fileReader。

标签: c++ visual-studio linker-errors


【解决方案1】:

看来,问题在于这两个项目的设置值不同

将 wchar_t 视为内置类型

将两个项目的 No (/Zc:wchar_t-) 设置为,解决了链接器错误。但我仍然不知道后果会是什么。

【讨论】:

  • MSDN 建议相反
  • 对于可能遇到此问题的任何其他人:检查您的预处理器中是否定义了_DEBUG。如果您定义了它,链接器将尝试与调试 CRT 链接。
【解决方案2】:

尝试使用 extern "C" 来声明 open 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 2011-02-09
    相关资源
    最近更新 更多