【问题标题】:Undefined Reference to Function in Library [duplicate]库中函数的未定义引用[重复]
【发布时间】:2014-09-02 17:53:30
【问题描述】:

我正在开发自己的数学库,并且我在用于库的命名空间中有几个非成员函数(“cml”,很重要)。无论如何,该库(我将其静态构建为 .a/.lib 文件)编译得很好,但是当我在测试程序中使用该库时,我收到一个错误,即函数是未定义的引用。

这是头文件(func.h):

namespace cml
{

template <typename T>
T toRadians(T val);
template <typename T>
T toDegrees(T val);

template <typename T>
T fastSqrt(T val);
template <typename T>
T fastInverseSqrt(T val);

}

这是 func.cpp 文件:

#include <CML/func.h>

#include <cmath>
#include <math.h>
#include <limits>
#include <cassert>

namespace cml
{

template <typename T>
T toRadians(T val)
{
    static_assert(std::numeric_limits<T>::is_iec559, "toRadians() requires the template parameters to be floating points.");

    return val * MATH_PI / 180;
}

template <typename T>
T toDegrees(T val)
{
    static_assert(std::numeric_limits<T>::is_iec559, "toDegrees() requires the template parameters to be floating points.");

    return val * 180 / MATH_PI;
}

template <typename T>
T fastSqrt(T val)
{
    static_assert(std::numeric_limits<T>::is_iec559, "fastSqrt() requires the template parameters to be floating points.");

    return T(1) / fastInverseSqrt(val);
}

template <typename T>
T fastInverseSqrt(T val)
{
    static_assert(std::numeric_limits<T>::is_iec559, "fastInverseSqrt() requires the template parameters to be floating points.");

    T tmp = val;
    T half = val * T(0.5);
    uint32* p = reinterpret_cast<uint32*>(const_cast<T*>(&val));
    uint32 i = 0x5f3759df - (*p >> 1);
    T* ptmp = reinterpret_cast<T*>(&i);
    tmp = *ptmp;
    tmp = tmp * (T(1.5) - half * tmp * tmp);
#if defined(CML_ACCURATE_FUNC) // If more accuracy is requested, run Newton's Method one more time
    tmp = tmp * (T(1.5) - half * tmp * tmp);
#endif // defined
    return tmp;
}

}

我收到所有四个函数的错误。我在 Windows8 上使用最新版本的 Code::Blocks 和 GCC。我正在为 Win32 编译。我尝试了我发现的不同建议,比如标记函数extern,但它似乎并没有解决它。我确定这是我缺少的一些简单的东西,如果是这种情况,第二双眼睛可能会有所帮助。

确切的错误:undefined reference tofloat cml::toRadians(float)'`

【问题讨论】:

  • 错误信息究竟是什么意思?
  • 哇,真不敢相信我忘记了,最重要的部分。我现在添加它。
  • 模板函数必须在头文件中——否则它们在编译时不能正确扩展——就像@SleuthEye 重复链接所说的那样......

标签: c++ gcc c++11 compiler-errors codeblocks


【解决方案1】:

您需要在头文件中定义模板函数。我会做的是

  1. 将 func.cpp 重命名为 func.inl,并确保它没有使用 C++ 编译器进行编译。
  2. #include "func.inl" 行添加到func.h 的底部。

模板函数不像常规函数那样编译,而是由稍后的编译阶段处理(如内联函数)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 1970-01-01
相关资源
最近更新 更多