使用 Catch 库无法解析的外部符号

Unresolved external symbol with Catch library

我正在迁移一些项目以使用 CMake build system. Now I'm adding project with some unit tests using the Catch library. It is header only library. The old Visual Studio project builds fine, but the new CMake project gives unresolved external symbol linker error. I have defined CATCH_CONFIG_MAIN in one of my source files. There are added all cpp files from other projects which are needed for the tests and all libraries on which other tested projects depend are linked. Despite this I have unresolved external symbol error only with generated from CMake 项目:

ChipCountTests.obj : error LNK2019: unresolved external symbol "public: __thiscall Catch::SourceLineInfo::SourceLineInfo(char const *,unsigned int)" (??0SourceLineInfo@Catch@@QAE@PBDI@Z) referenced in function "void __cdecl `anonymous namespace'::`dynamic initializer for 'autoRegistrar1''(void)" (??__EautoRegistrar1@?A0xb4291ec5@@YAXXZ)
1>FlyingChipRewardCalculatorUT.obj : error LNK2001: unresolved external symbol "public: __thiscall Catch::SourceLineInfo::SourceLineInfo(char const *,unsigned int)" (??0SourceLineInfo@Catch@@QAE@PBDI@Z)

显然我缺少从 vcxprojCMakeLists.txt 添加一些配置,但我目前无法弄清楚。

从您提供的上下文中推断出具体问题有点困难,但 here 是 CMake 集成的官方 Catch 指令。

根据我与 Visual Studio 一起使用的经验 - 集成很顺利。

在我的一个文件中我有:

#define CATCH_CONFIG_MAIN
#include <catch.hpp>

但我还使用 CMake 宏将预编译 header 添加到项目中:

add_precompiled_header (${TARGET_NAME}
  ${CMAKE_CURRENT_SOURCE_DIR}/StdAfx.h
  ${CMAKE_CURRENT_SOURCE_DIR}/StdAfx.cpp)

此宏强制在所有文件中包含预编译的 header,但其中我有 #include <catch.hpp> 而没有 #define CATCH_CONFIG_MAIN,除一个文件外,所有文件都需要它。

我向宏添加了选项以传递不包含预编译的文件列表header,这解决了问题。

当我尝试在我的测试项目中启用预编译 Header 选项的情况下使用 Catch 时,我最终遇到链接器错误 LNK2019。

我仍然在我的项目中使用 stdafx.h 并禁用预编译 header 选项以便构建项目。

Right-click 项目 -> 配置属性 -> C/C++-> 预编译 Headers -> 预编译 Header -> 不使用预编译 Headers.

我有同样的错误,我通过将目标链接到 Catch2WithMain 解决了这个问题

target_link_libraries( ${PROJECT_TEST} Catch2 Catch2WithMain)
set_property(TARGET ${PROJECT_TEST} PROPERTY CXX_STANDARD 14)
set_property(TARGET ${PROJECT_TEST} PROPERTY CXX_EXTENSIONS OFF)