将 QString 与 wchar_t 一起使用时无法解析的外部符号

Unresolved external symbol when using QString with wchar_t

以下代码无法在 Visual Studio 中 link:

#include <qstring.h>

int main(int argc, char *argv[])
{
  const auto qstr = QString::fromWCharArray(L"Hello world!");

  auto wstr = new wchar_t[qstr.length() + 1];
  const auto wlen = qstr.toWCharArray(wstr);
  wstr[wlen] = L'[=11=]';

  return 0; // 'wstr' not deleted for simplification
}

error LNK2019: unresolved external symbol "__declspec(dllimport) public: int __thiscall QString::toWCharArray(unsigned short *)const " (__imp_?toWCharArray@QString@@QBEHPAG@Z) referenced in function _main

error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QString __cdecl QString::fromWCharArray(unsigned short const *,int)" (__imp_?fromWCharArray@QString@@SA?AV1@PBGH@Z) referenced in function _main

项目设置为不将 wchar_t 视为内置类型 (No /Zc:wchar_t-)。

将值更改为 Yes /Zc:wchar_t 可解决链接错误。它也适用于 QString::toStdWStringQString::fromStdWString.


我正在记录从旧项目迁移时经常发现的这个问题。