0

我正在尝试使用 Catch2 测试来测试我的程序并使用 CMake 构建应用程序。当未实施 Catch2 测试时,该程序可以运行并且应用程序将被构建。一旦我实现了 Catch2 测试,应用程序将不再构建。我包含#define CONFIG_CATCH_MAIN#include "catch.hpp"进入 main.cpp。

但是当我尝试构建包含测试的应用程序时,我总是会得到这样的结果:

CMakeFiles\intent_recognition.dir/objects.a(main.cpp.obj):main.cpp:(.text+0x43d): 未定义引用Catch::StringRef::StringRef(char const*)' CMakeFiles\intent_recognition.dir/objects.a(main.cpp.obj):main.cpp:(.text+0x4b9): undefined reference to Catch::AssertionHandler::AssertionHandler(Catch::StringRef const&, Catch::SourceLineInfo const& , Catch::StringRef, Catch::ResultDisposition::Flags)'

我不知道发生了什么...

我的 main.cpp 文件如下所示:

#define CONFIG_CATCH_MAIN
#include "catch.hpp"

#include <iostream>
#include <string>
#include "Intent.h"

std::string func (std::string input)
{
    std::cout << input << std::endl;

    Intent IntentObj = Intent(input);       // create Intent Object with input

    IntentObj.analyze();

    return IntentObj.result();
}

TEST_CASE("Get Weather", "[func]")
{
    REQUIRE( func("What is the weather like today?") == "Intent: Get Weather" );
    REQUIRE( func("Tell me what the weather is like.") == "Intent: Get Weather") ;
    REQUIRE( func("I want to know the weather for tomorrow") == "Intent: Get Weather" );
    REQUIRE( func("Can you tell me the weather for Wednesday?") == "Intent: Get Weather") ;
} 

我的 CMakeLists.txt 看起来像这样:

cmake_minimum_required(VERSION 3.20.2)

project(intent_recognition)

add_executable(intent_recognition main.cpp)
4

2 回答 2

1

快速浏览一下Catch2 教程,您至少错过了要链接的 Catch2 库的规范。该教程指出,您至少需要拥有上面的文件似乎遗漏的代码:

find_package(Catch2 REQUIRED)
add_executable(tests test.cpp)
target_link_libraries(tests PRIVATE Catch2::Catch2)

您的target_link_libraries...示例中缺少 。这可能就是您收到这些链接器错误的原因。这find_package将在名称下引入库,Catch2::Catch2然后您可以将其链接到您的测试可执行文件。如果find_package command在您的设置中不起作用,您可能需要检查您是如何安装 Catch2 的。

于 2021-05-03T07:55:28.540 回答
0

我假设您想将 Catch2 用作仅标头库。问题可能是因为您包含include/catch.hpp而不是single_include/catch2/catch.hpp

于 2021-05-03T10:20:47.773 回答