C++ 链接器找不到函数声明(未定义引用)

C++ linkeditor can't find function declaration (undefined reference)

我正在学习 C++ 并使用 CLion 构建项目。我在 main 目录中有 main.cpp 文件。我还有一个 main/Objects 目录,里面有 Vec3.hVec3.cpp 文件:

//Vec3.h
template<typename T>
class Vec3
{
public:
    // 3 most basic ways of initializing a vector
    Vec3() : x(T(0)), y(T(0)), z(T(0)) {}
    Vec3(const T &xx) : x(xx), y(xx), z(xx) {}
    Vec3(T xx, T yy, T zz) : x(xx), y(yy), z(zz) {}
    T x, y, z;

    T length();
};

.

//Vec3.cpp
#include "Vec3.h"
#include <stdio.h>
#include <math.h>

template <typename T>
T Vec3<T>::length()
{
    return sqrt(x * x + y * y + z * z);
}

.

//main.cpp
#include <iostream>
#include "Objects/Vec3.h"

int main() {
    Vec3<double> vec(3, 4, 0);
    std::cout << "Hello, World!" << std::endl;
    std::cout << vec.length() << std::endl;
    return 0;
}

.

//CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project(Testing)

set(CMAKE_CXX_STANDARD 14)

set(SOURCE_FILES main.cpp Objects/Vec3.cpp)

add_executable(Testing ${SOURCE_FILES})

当我尝试构建 运行 时,出现以下错误:

undefined reference to "Vec3<double>::length()". ld returned 1 exit status

哪些信息我没有提供给链接编辑器?

你还没有告诉 CMake 关于你的 header 文件,所以你可以使用 target_include_directories。将以下行添加到 CMakeLists.txt 文件的末尾,以确保 header 包含在构建中:

target_include_directories(Testing PRIVATE Objects)

此外,模板化定义通常可以 only be implemented 在 header 文件中。将以下函数定义从 Vec3.cpp 文件移动到 header 文件 (Vec3.h):

template <typename T>
T Vec3<T>::length()
{
    return sqrt(x * x + y * y + z * z);
}