2015-04-01 56 views
0

我想在C++中構建一個raytracer,並且其中一個類有編譯問題。基本程序運行良好,如果所有的代碼被存儲在頭文件,但一旦在我其相應的CPP文件移動它它給這個錯誤:添加cpp文件後架構x86_64的未定義符號

g++ -O3 -c main.cpp -I "./" 
g++ main.o -o raytracer.exe 
Undefined symbols for architecture x86_64: 
"Plane::Plane(Vect, double, Color)", referenced from: 
    _main in main.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 
make: *** [raytracer] Error 1 

從報頭文件中的代碼(Plane.h)是:

#ifndef PLANE_H 
#define PLANE_H 

#include "math.h" 
#include "Object.h" 
#include "Vect.h" 
#include "Color.h" 

class Plane : public Object 
{ 
private: 
    Vect normal; 
    double distance; 
    Color color; 

public: 
    Plane(); 

    Plane(Vect n, double d, Color c); 

    Vect GetPlaneNormal()  { return normal; } 
    double GetPlaneDistance() { return distance; } 
    virtual Color GetColor() { return color; } 

    virtual Vect GetNormalAt(Vect point); 

    virtual double FindIntersection(Ray ray); 
}; 

#endif // PLANE_H 

和執行(Plane.cpp):

#include "Plane.h" 

Plane::Plane() 
{ 
    normal = Vect(1.0, 0.0, 0.0); 
    distance = 0.0; 
    color = Color(0.5, 0.5, 0.5, 0.0); 
} 

Plane::Plane(Vect n, double d, Color c) 
{ 
    normal = n; 
    distance = d; 
    color = c; 
} 

Vect Plane::GetNormalAt(Vect point) 
{ 
    return normal; 
} 

double Plane::FindIntersection(Ray ray) 
{ 
    Vect rayDirection = ray.GetRayDirection(); 

    double a = rayDirection.DotProduct(normal); 
    if (a == 0) 
    { 
      // ray is parallel to our plane:w 
     return -1; 
    } 
    else 
    { 
     double b = normal.DotProduct(ray.GetRayOrigin().VectAdd(normal.VectMult(distance).Negative())); 
     return -1 * b/a - 0.000001; 
    } 
} 

請問有什麼需要添加,使問題消失?謝謝!

回答

1

您需要包括plane.cpp在編譯命令

g++ -c main.cpp plane.cpp 

然後鏈接兩個對象文件

g++ -o raytracer main.o plane.o 

或者,更好,學習如何使用一些現代的構建系統,如CMake,它將來會非常方便。

1

g++ main.o -o raytracer.exe

你的Plane.cpp函數大概是編譯到plane.o中的。鏈接器抱怨,因爲你沒有給它plane.o鏈接。嘗試:

g++ <put all your .o files here> -o raytracer.exe 

...或者只是編譯和鏈接所有在一個去。

g++ <put all your .cpp files here> -O3 -I "./" -o raytracer.exe 

(即編譯不-c標誌)

相關問題