我在文件 templates.hpp 中的数组定义如下
#include <cstddef>
#include <iostream>
using namespace std;
template <typename T>
class Array {
private:
T* elements;
size_t count;
public:
Array(size_t size);
Array(const Array& other);
Array(Array&& other);
virtual ~Array();
T& operator[](size_t index);
const T& operator[](size_t index) const;
Array& operator=(const Array& other);
Array&& operator=(Array&& other);
size_t size() { return count; }
};
下面是我的templates.cpp文件
#include "templates.hpp"
#include <iostream>
#include <cstddef>
using namespace std;
template <typename T>
Array<T>::Array(size_t arraySize)
try: elements { new T[arraySize]}, count {arraySize} {
cout<< "sucessfully created the array" << endl;
}
catch(const exception& e){
cerr << " Memory Allocation failure in Array Constructor." << endl;
}
template <typename T>
inline Array<T>::Array(const Array &other) try : elements {
new T[other.size()]}, count { other.size }
{
cout<< "sucessfully created the array" << endl;
}
catch(const exception& e ) {
}
我正在使用 catch2 库来测试我的代码。下面是我的 templates_test.cpp 文件。
#include <iostream>
#include <memory>
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "templates.hpp"
#include <cstddef>
using namespace std;
TEST_CASE("initialize the array", "Array init") {
Array<int> data {(size_t)5};
}
我正在使用 cmake 来构建这个项目并进行测试。我的 CMakeLists.txt
文件是 -
cmake_minimum_required(VERSION 3.20 FATAL_ERROR)
project(chapter-01 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
add_library(templates templates.hpp templates.cpp)
add_executable(templates_test templates_test.cpp catch.hpp)
target_link_libraries(templates_test templates)
enable_testing()
add_test(NAME catch_template_test COMMAND $<TARGET_FILE:templates_test> --success)
我创建了构建目录并在构建目录中运行 cmake 命令。
cmake ..
工作正常。我运行 cmake --build .
命令失败。
以下是错误跟踪。
cmake --build 。 18:09:50
整合编译器生成的目标模板的依赖关系
[ 50%] 构建目标模板
整合编译器生成的目标templates_test的依赖
[ 75%] 构建 CXX 对象 CMakeFiles/templates_test.dir/templates_test.cpp.o
[100%] 链接 CXX 可执行模板_测试
/usr/bin/ld: CMakeFiles/templates_test.dir/templates_test.cpp.o: 在函数中 ____C_A_T_C_H____T_E_S_T____0()': templates_test.cpp:(.text+0x19eee): undefined reference to
Array::Array(unsigned long)'
/usr/bin/ld: templates_test.cpp:(.text+0x19f52): 对 Array<int>::~Array()' /usr/bin/ld: templates_test.cpp:(.text+0x19f92): undefined reference to
Array::~Array()' 的未定义引用
collect2: 错误: ld 返回 1 个退出状态
make[2]: *** [CMakeFiles/templates_test.dir/build.make:98: templates_test] 错误 1
make1: *** [CMakeFiles/Makefile2:85: CMakeFiles/templates_test.dir/all] 错误 2
make: *** [Makefile:101: all] 错误 2
我查看了此 stackoverflow 帖子及其原始帖子。我正在使用 cmake,那些帖子作者使用 gcc 直接编译。
另外,我也在 add_library 中添加了两个文件 templates.hpp templates.cpp。
我该如何解决这个问题?