首页 > 解决方案 > Catch2 - 未定义的引用

问题描述

我正在使用 Catch2 作为库测试我的项目。我遵循了 Catch 文档中的每一步,但是当我运行测试时,我收到以下错误:

CMakeFiles/tests.dir/tests/IntegerIntervalTest.cpp.o: in function "____C_A_T_C_H____T_E_S_T____0()": /home/davide/cpp-project/tests/IntegerIntervalTest.cpp:8: undefined reference to "domain::IntegerAbstractInterval<int, int>::IntegerAbstractInterval(int, int)"

并且对于测试“类”中的每个方法调用都会重复此错误。

CMakeLists:

PROJECT(cpp_project)
CMAKE_MINIMUM_REQUIRED(VERSION 3.5)
INCLUDE(CheckCXXCompilerFlag)

CHECK_CXX_COMPILER_FLAG(-std=c++14 COMPILER_SUPPORTS_CXX14)
IF (COMPILER_SUPPORTS_CXX14)
    ADD_COMPILE_OPTIONS("-std=c++14")
ELSE ()
    MESSAGE(FATAL_ERROR "Compiler ${CMAKE_CXX_COMPILER} has no C++14 support.")
ENDIF ()


set(BASE_SRCS src/Bound.cpp src/Bound.hpp src/Infinity.cpp src/Infinity.hpp src/AbstractInterval.cpp src/AbstractInterval.hpp
        src/UndefinedOperationException.hpp src/IntegerAbstractInterval.cpp src/IntegerAbstractInterval.hpp src/FloatingPointAbstractInterval.cpp
        src/FloatingPointAbstractInterval.hpp)
ADD_COMPILE_OPTIONS("-Wall" "-Wextra" "-Wpedantic" "-Werror" )
ADD_LIBRARY(cpp-project ${BASE_SRCS})
INCLUDE_DIRECTORIES(libs/variant/include)


set(EXECUTABLE_OUTPUT_PATH bin)
set(CATCH_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/catch)
add_library(Catch INTERFACE)
target_include_directories(Catch INTERFACE ${CATCH_INCLUDE_DIR})
set(TEST_SRCS tests/InfinityTest.cpp tests/IntegerIntervalTest.cpp)
add_executable(tests ${BASE_SRCS} ${TEST_SRCS})
target_link_libraries(tests Catch)

这是测试文件IntegerIntervalTest.cpp

#include "../src/IntegerAbstractInterval.hpp"
#include "../libs/catch2/catch.hpp"

using namespace domain;


TEST_CASE("Operations on IntegerInterval instances", "[IntegerAbstractInterval]") {
    IntegerAbstractInterval<int, int> i(0,1);
    IntegerAbstractInterval<Infinity, Infinity> ii(Infinity('-'), Infinity('+'));
    IntegerAbstractInterval<Infinity, int> iii(Infinity('-'), 5);
    IntegerAbstractInterval<int, Infinity> iv(0, Infinity('+'));
    IntegerAbstractInterval<int, int> v(-1,1);

    SECTION("Sum operations") {
        auto res1 = i + v;
        REQUIRE(res1.getLowerBound() == Bound(-1));
        REQUIRE(res1.getUpperBound() == Bound(2));
    }
}

标签: c++testingundefined-referencecatch-unit-test

解决方案


我有同样的问题,它是通过首先定义#define然后定义的#include

#define CATCH_CONFIG_MAIN
#include "catch.hpp"

for IDECatch2提供了一个很好的设置和使用教程。JetBrainsCLion


推荐阅读