简体   繁体   中英

Catch2 test don't work when building application with CMake

I'm trying to test my program by using Catch2 tests and build the application using CMake. The program works and the application gets build when the Catch2 tests are not implemented. Once I implemented the Catch2 tests, the application won't build anymore. I included #define CONFIG_CATCH_MAIN and #include "catch.hpp" into main.cpp.

But I always get something like this when I try to build the application with the tests included:

CMakeFiles\intent_recognition.dir/objects.a(main.cpp.obj):main.cpp:(.text+0x43d): undefined reference to 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)'

I don't know what's going...

My main.cpp file looks like this:

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

My CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.20.2)

project(intent_recognition)

add_executable(intent_recognition main.cpp)

Having a quick look at the Catch2 tutorial you are at least missing the specification of the Catch2 library to link. The tutorial states that you are at least need to have this code which your file above seems to miss:

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

The target_link_libraries... is missing in your example. That's probably why you are getting those linker errors. The find_package will introduce the library under the name Catch2::Catch2 which you can then link to your test executable. If the find_package command is not working in your setup, you may need to check how you did install Catch2.

I'm assuming that you want to use Catch2 as a header only library. The problem may be because you are including include/catch.hpp instead of single_include/catch2/catch.hpp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM