Search code examples
c++catch-unit-testcatch2

catch2 throws and error when adding a struct


This is the root of my project. I think I am missing a basic concept because the error occur when I wrap the the find() function in a struct.

  CMakeLists.txt
  bst.cpp
  bst.hpp
  bst-test.cpp
  catch.hpp

CMakeLists.txt

cmake_minimum_required(VERSION 3.16.4 FATAL_ERROR)

project(bst LANGUAGES CXX)

set(CMAKE_CXX_COMPILER clang++)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_library(bst bst.cpp)

add_executable(bst-test bst-test.cpp)
target_link_libraries(bst-test bst)

enable_testing()

add_test(
         NAME catch_test
         COMMAND $<TARGET_FILE:bst-test> --success
         )

bst.cpp

struct Bst {
  int find(int num, int array[]) { return -1; }
};

bst.hpp

struct Bst {
  int find(int num, int array[]);
};

bst-test.cpp

#include "bst.hpp"
#define CATCH_CONFIG_MAIN
#include "catch.hpp"

TEST_CASE("The number to search is not found in the list", "[notFound]") {
  int array[]{};
  Bst tree;
  REQUIRE(tree.find(1, array) == -1);
}

This is the error when trying to compile.

CMakeFiles/bst-test.dir/bst-test.cpp.o: In function `____C_A_T_C_H____T_E_S_T____0()':
bst-test.cpp:(.text+0x2b0b5): undefined reference to `Bst::find(int, int*)'
clang-11: error: linker command failed with exit code 1 (use -v to see invocation)
CMakeFiles/bst-test.dir/build.make:84: recipe for target 'bst-test' failed
make[2]: *** [bst-test] Error 1
CMakeFiles/Makefile2:104: recipe for target 'CMakeFiles/bst-test.dir/all' failed
make[1]: *** [CMakeFiles/bst-test.dir/all] Error 2
Makefile:94: recipe for target 'all' failed
make: *** [all] Error 2

Solution

  • you are declaring the Bst structure again in your .cpp file. The source file should only contain the definition of the methods, not the declaration of the structure.

    Changing bst.cpp to the following fixes the error:

    #include "bst.hpp"
    int Bst::find(int num, int array[]) { return -1; }