2009-07-31 4 views
4

저는 계산을 수행하기 위해 VectorMath 클래스에 정적 메서드를 호출하는 Vector3D 클래스를 작성하고 있습니다. 내가 컴파일 할 때,이 얻을 :정적 메서드에 대한 C++ 링커 문제

 
bash-3.1$ g++ VectorMath.cpp Vector3D.cpp 
/tmp/cc5cAPia.o: In function `main': 
Vector3D.cpp:(.text+0x4f7): undefined reference to 'VectorMath::norm(Vector3D*)' 
collect2: ld returned 1 exit status 

코드 :

VectorMath.h :

#ifndef VECTOR3D_H 
#include "Vector3D.h" 
#endif 

class VectorMath { 
    public: 
    static Vector3D* calculatePerpendicularVector(Vector3D*, Vector3D*); 
    static Vector3D* norm(Vector3D*); 
    static double length(Vector3D*); 
}; 

VectorMath.cpp

#include "VectorMath.h" 
Vector3D* norm(Vector3D* vector) { // can't be found by linker 
    // do vector calculations 
    return new Vector3D(xHead, yHead, zHead, xTail, yTail, zTail); 
} 
// other methods 

값 Vector3D. cpp

#include "Vector3D.h" 
#include "VectorMath.h" 
// ... 
// vector implementation 
// ... 
int main(void) { 
    Vector3D* v = new Vector3D(x, y, z); 
    Vector3D* normVector = VectorMath::norm(v); // error here 
}   

왜 링커가 VectorMath::norm 메서드를 찾지 못합니까?

+0

이것은 "그러나 도움이되지 않습니다 ..."는 정보가 충분하지 않습니다. 그게 무슨 뜻 이죠? 같은 오류, 다른 오류? – GManNickG

답변

14

당신이 놓치고 :

//VectorMath.cpp 
#include "VectorMath.h" 

      | 
      V - here 
Vector3D* VectorMath::norm(Vector3D* vector) 
{ 
    ... 
} 

norm 기능 VectorMath::의 일부입니다 당신이해야 할 것은 정의에 메소드 이름을 규정입니다. 그것 없이는, 당신은 단지 자유로운 기능을 가지고 있습니다.


이것은 디자인에 관한 것이지만 모든 것에 대한 포인터를 사용하는 이유는 무엇입니까? 이것은 훨씬 더 깨끗합니다 :

class VectorMath { 
    public: 
    static Vector3D norm(const Vector3D&); 
}; 

참고 자료를 참조하면 C++을 사용하므로 C 코드를 작성하지 마십시오. 내가 이것을 부르면 어떻게 될까?

VectorMath::norm(0); // null 

크래시가 발생합니다. 수표를 넣어야합니다. 어떤 경우에 반환해야합니까? 이것은 모두 참조를 사용하여 정리됩니다.

또한 Vector3D 클래스의 구성원 만 만들면 안됩니까?

Vector3D* v = new Vector3D(x, y, z); 
v->norm(); // normalize would be better, in my opinion 

마지막으로 스택을 할당합니다.RAII 개념이에

int main(void) { 
    Vector3D* v = new Vector3D(x, y, z); 
    Vector3D* normVector = VectorMath::norm(v); 

    // delete v; 
    //^you're not deleting it! 
}   

변경을하고, 사용 :

int main(void) { 
    Vector3D v(x, y, z); 
    Vector3D* normVector = VectorMath::norm(v); 

    // delete v; 
    //^you're not deleting it! 
}  

그리고 norm 당신이 매우 깨끗 코드로 끝날 멤버 함수를함으로써 :

를 코드는 지금 메모리 누수가
int main(void) { 
    Vector3D v(x, y, z); 
    Vector3D normVector(v.norm()); 
}  

모든 포인터가 누출되지 않고 모두 섹시합니다.

+0

] 감사합니다. 작동하는 것 같습니다. 나는 그것을 전에 시도했지만 실패했다. -하지만 지금은 작동 중이다. 메모리 누수에 대한 조언을 주셔서 감사합니다 ... 나는 그 것에 대해 새로운 질문을 할 것입니다. –

+0

@Gman, 인상적인 답변 :) – mahesh

4

당신은 VectorMath.cppVector3D::norm 방법을 정의하지 않은 ...

Vector3D* VectorMath::norm(Vector3D* vector) { 

을하지만 그 중 하나가 도움이되지 않습니다 : 언뜻보기에 나는이 같은 규범을 선언 할 필요가 거라고 생각하는 것입니다. 대신 norm이라는 전역 함수를 정의했습니다.

Vector3D* Vector3D::norm(Vector3D* vector) 
+0

나보다 24 초 빠릅니다. : [ – GManNickG

0
Vector3D* VectorMath::norm(Vector3D* vector) { // can't be found by linker 
    // do vector calculations 
    return new Vector3D(xHead, yHead, zHead, xTail, yTail, zTail); 
} 
관련 문제