我今天遇到了一个很奇怪的问题。我有一个为SSE优化的数学库,因此几乎所有的功能都声明为内联。为了简化起见,我只使用一个类Vector3来解释这个问题:
Vector3在Vector3.h中声明,如下所示:
#ifndef VIRTUS_VECTOR3_H
#define VIRTUS_VECTOR3_H
#ifndef VEC3INLINE
#if(_DEBUG)
#define VEC3INLINE inline
#else
#define VEC3INLINE __forceinline
#endif
#endif
namespace Virtus {
struct Vector3
{
union
{
struct { f32 x,y,z; };
f32 v[3];
};
Vector3(void);
Vector3(const Vector3& rhs);
Vector3(f32 xx, f32 yy, f32 zz);
VEC3INLINE Vector3& operator=(const Vector3& rhs);
VEC3INLINE Vector3 operator+(f32 rhs) const;
VEC3INLINE Vector3 operator-(f32 rhs) const;
VEC3INLINE Vector3 operator*(f32 rhs) const;
VEC3INLINE Vector3 operator/(f32 rhs) const;
VEC3INLINE Vector3& operator+=(f32 rhs);
VEC3INLINE Vector3& operator-=(f32 rhs);
...
#include "vector3.inl"
#endif在vector3.inl中,我继续定义所有函数
namespace Virtus {
Vector3::Vector3(void)
: x(0.0f), y(0.0f), z(0.0f)
{
}
Vector3::Vector3(const Vector3& rhs)
: x(rhs.x), y(rhs.y), z(rhs.z)
{
}
Vector3::Vector3(f32 xx, f32 yy, f32 zz)
: x(xx), y(yy), z(zz)
{
}
VEC3INLINE Vector3& Vector3::operator=(const Vector3& rhs)
{
memcpy(v, rhs.v, sizeof(v));
return *this;
}
...然后,我将所有数学对象包含在一个名为math.h的文件中。
#ifndef VIRTUS_MATH_H
#define VIRTUS_MATH_H
#include "vector2.h"
#include "vector3.h"
#include "vector4.h"
#include "matrix4.h"
#include "primesearch.h"
namespace Virtus
{
class MathException
{
public:
enum ErrorCode
{
PRIME_SEARCH_INVALID_ELEMENTS,
PRIME_SEARCH_UNSUFFNUM_PRIMES
};
MathException(ErrorCode code) : m_Error(code) {}
ErrorCode What(void) const { return m_Error; }
private:
ErrorCode m_Error;
};
} // namespace virtus
#endif // Include Guard和math.h包含在我预编译的头文件中(preed.h,也就是stdafx.h)
我使用Visual 2008,它将自动从构建过程中排除.inl文件。
这是我收到的链接器错误:
错误1错误LNK2005:"public:__thiscall Virtus::Vector3::Vector3(void)“(?0Vector3@ Virtus @@QAE@XZ)已在precompiled.obj main.obj Virtus中定义
我尝试了几乎所有可以想象的方法来修复这个问题,比如手动将所有inl文件排除在构建之外;在预编译的文件中不包括math.h,但只在我需要它的地方(在这种情况下,我得到一个类似的已经定义的链接器错误);从inl扩展到cpp扩展,等等。我能够修复它的唯一方法是使用#实用化一次,而不是包含警卫。因此,我目前最好的猜测是,它与预编译的头文件和包含保护的组合有关,但我不太确定如何解决这个问题。
我会非常感谢你的帮助!
发布于 2011-06-24 22:51:03
在vector3.inl中的每个定义都需要使用inline显式定义。
https://stackoverflow.com/questions/6474480
复制相似问题