对库中函数的未定义引用

Undefined Reference to Function in Library

本文关键字:未定义 引用 函数      更新时间:2023-10-16

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

这是头文件:

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);
}

这是函数。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;
}
}

我得到了所有四个函数的错误。我正在使用最新版本的Code::Blocks,在Windows8上使用GCC。我正在编译Win32。我试过不同的建议,我发现像标记功能extern,但它似乎没有解决它。我肯定是缺少了一些简单的东西,如果是这样的话,另一双眼睛可能会有所帮助。

undefined reference to float cml::toRadians(float)' '

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

  1. 将function .cpp重命名为function。
  2. 在function .h底部添加#include "func.inl"

模板函数不像普通函数那样编译,而是在后面的编译阶段处理(像内联函数)。