2015-04-01 68 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标志)

相关问题