catch2单包含导致测试中出现“未定义引用”

时间:2019-05-18 00:10:25

标签: c++ cmake catch2

我已经看到很多具有相同问题的示例,但是它们不适用于我的情况。

我具有以下文件结构:

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);
}

所有这些看起来都很好,并且基本上是我为此找到的许多指南的复制/粘贴。但是,出现以下问题:

[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)'

因此,显然,它能够链接到catch.hpp,否则它将找不到任何这些东西。显然我正在使用catch的single_include版本,这是我发现同一问题的所有示例的问题。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

#define CATCH_CONFIG_MAIN行告诉catch.h标头它也应该发出Catch实现。但是为此,此行应该之前出现,包括catch.h

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