catch2 单包含导致测试中 "undefined reference"

catch2 single-include causes "undefined reference" in test

我见过很多关于相同问题的例子,但它们并不适用于我的情况。

我有以下文件结构:

unit-tests/CMakeLists.txt
unit-tests/FlaAlgoTests/CMakeLists.txt
unit-tests/FlaAlgoTests/catch_test_runner.cpp

Proj/CMakeLists.txt中:

ExternalProject_Add(
        catch
        PREFIX ${CMAKE_BINARY_DIR}/catch2
        GIT_REPOSITORY https://github.com/catchorg/Catch2.git
        TIMEOUT 10
        UPDATE_COMMAND ${GIT_EXECUTABLE} pull
        CONFIGURE_COMMAND ""
        BUILD_COMMAND ""
        INSTALL_COMMAND ""
        LOG_DOWNLOAD ON
)
ExternalProject_Get_Property(catch source_dir)
include_directories(${source_dir}/single_include/catch2)

并且在 Proj/TestDir1/CMakeLists.txt 中:

add_executable(
        catch_test_runner
        catch_test_runner.cpp
)

其中 catch_test_runner.cpp 是:

#include <iostream>
#include "catch.hpp"

#define CATCH_CONFIG_MAIN

TEST_CASE("Yeet", "[beep]"){
    REQUIRE(true);
    REQUIRE(2 == 1);
}

所有这些看起来都非常好,而且基本上是 copy/paste 我为此找到的众多指南的一部分。但是,我遇到以下问题:

[100%] Linking CXX executable catch_test_runner.exe
CMakeFiles/catch_test_runner.dir/catch_test_runner.o: In function `::____C_A_T_C_H____T_E_S_T__(void)':
/cygdrive/c/Users/dbak/Projects/firmware/unit-tests/FlaAlgoTests/catch_test_runner.cpp:7: undefined reference to `Catch::StringRef::StringRef(char const*)'
/cygdrive/c/Users/dbak/Projects/firmware/unit-tests/FlaAlgoTests/catch_test_runner.cpp:7:(.text+0x32): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `Catch::StringRef::StringRef(char const*)'
/cygdrive/c/Users/dbak/Projects/firmware/unit-tests/FlaAlgoTests/catch_test_runner.cpp:7: undefined reference to `Catch::AssertionHandler::AssertionHandler(Catch::StringRef const&, Catch::SourceLineInfo const&, Catch::StringRef, Catch::ResultDisposition::Flags)'

所以,显然它可以link到catch.hpp,否则它就找不到这些东西了。显然我使用的是 single_include 版本的 catch,这是我发现的所有具有相同问题的示例的问题。

我做错了什么?

#define CATCH_CONFIG_MAIN 告诉 catch.hpp header 它也应该发出 Catch 实现。但为此目的,这一行应该在 之前 包括 catch.hpp:

#define CATCH_CONFIG_MAIN // This should come **before** including the 'catch.hpp'.
#include "catch.hpp"