【问题标题】:C++ linkeditor can't find function declaration (undefined reference) [duplicate]C ++linkeditor找不到函数声明(未定义的引用)[重复]
【发布时间】:2019-12-16 04:55:05
【问题描述】:

我正在学习 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

我没有向链接器提供什么信息?

【问题讨论】:

    标签: c++ cmake linker undefined-reference


    【解决方案1】:

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

    target_include_directories(Testing PRIVATE Objects)
    

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

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

    【讨论】:

    • CMake 现在抛出以下错误:“target_include_directories called with invalid arguments”
    • @FranciscoJoséLetterio 由答案更新。此外,请确保在调用 add_executable() 之后将此行添加到 CMakeLists.txt 文件的末尾。
    • 好的,在 CMake 中添加 PRIVATE 不会引发错误。但是,未定义的引用错误仍然存​​在
    • @FranciscoJoséLetterio 忘记了模板定义...在您的示例中,Vec3.cpp 可以用作占位符文件,但您必须将 length() 函数定义移动到头文件中。请参阅链接的answer。
    猜你喜欢
    • 2018-02-04
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    相关资源
    最近更新 更多