添加cpp文件后,架构x86_64的未定义符号

时间:2015-04-01 23:00:19

标签: c++ linker-errors

我试图在c ++中构建一个光线跟踪器,并且我在其中一个类上遇到了编译问题。基本上,如果所有代码都存储在头文件中,程序运行良好,但是一旦我在相应的cpp文件中移动它就会出现这个错误:

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

我是否需要添加任何内容才能使问题消失?谢谢!

2 个答案:

答案 0 :(得分:1)

您需要在编译命令中包含plane.cpp

g++ -c main.cpp plane.cpp

然后链接两个目标文件

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

或者,更好的是,学习如何使用一些现代的构建系统,例如CMake,它将来会非常方便。

答案 1 :(得分: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标志编译)