0

这是我项目的根源。我认为我缺少一个基本概念,因为当我将find()函数包装在结构中时会发生错误。

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

这是尝试编译时的错误。

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
4

1 回答 1

1

Bst您在 .cpp 文件中再次声明结构。源文件应该只包含方法的定义,而不是结构的声明。

更改bst.cpp为以下内容可修复错误:

#include "bst.hpp"
int Bst::find(int num, int array[]) { return -1; }
于 2020-11-10T08:05:34.103 回答