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

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

本文关键字:未定义 引用 声明 链接 编辑器 找不到 函数 C++      更新时间:2023-10-16

我正在学习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 你的头文件,所以你可以使用target_include_directories.将以下行添加到CMakeLists.txt文件的末尾,以确保标头包含在生成中:

target_include_directories(Testing PRIVATE Objects)

此外,模板化定义通常只能在头文件中实现。将以下函数定义从Vec3.cpp文件移动到头文件 (Vec3.h(:

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