C++链接编辑器找不到函数声明(未定义的引用)
C++ linkeditor can't find function declaration (undefined reference)
我正在学习C++并使用CLion来构建项目。我在main
目录中有main.cpp
文件。我还有一个main/Objects
目录,其中有Vec3.h
和Vec3.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);
}
相关文章:
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 对 Scalar ::Scalar() 的未定义引用
- 对复制 CTOR 和 CTOR 的未定义引用
- 对显式实例化的模板函数的未定义引用
- TensorRT (C++ API) 对"createNvOnnxParser_INTERNAL"的未定义引用
- 2个模板化类的非模板友元函数未定义引用错误
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 获取对function_name的未定义引用
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- 对结构方法的未定义引用
- 使用内联函数 c++ 的未定义引用
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 对 DLOPEN 的未定义引用
- QT C++中对全局变量的未定义引用
- 快速数学导致对"__pow_finite"的未定义引用
- 对 boost::system::d etail::system_category_instance 的未定义引用,从
- OpenCV 3.4.3 中对 'cv::String::d eallocate()' 错误的未定义引用