C++ 对构造函数和析构函数的未定义引用
我只见过人们在构建时没有将他们的类对象链接在一起造成的这种情况,但我见过,我不确定是什么问题 资料来源:C++ 对构造函数和析构函数的未定义引用,c++,linker,g++,C++,Linker,G++,我只见过人们在构建时没有将他们的类对象链接在一起造成的这种情况,但我见过,我不确定是什么问题 资料来源: //test.cpp #include "Point.h" #include "Sphere.h" #include "Scene.h" int main(){ Sphere s; Scene sc; sc.img_plane.upper_left = Point(-1, 1, -3); sc.img_plane.upper_right = Point(1
//test.cpp
#include "Point.h"
#include "Sphere.h"
#include "Scene.h"
int main(){
Sphere s;
Scene sc;
sc.img_plane.upper_left = Point(-1, 1, -3);
sc.img_plane.upper_right = Point(1, 1, -3);
sc.img_plane.lower_left = Point(-1, -1, -3);
sc.img_plane.lower_right = Point(1, -1, -3);
sc.width = 100;
sc.height = 100;
return 0;
}
错误:
test.cpp:(.text+0x17): undefined reference to `Sphere::Sphere()'
test.cpp:(.text+0x26): undefined reference to `Scene::Scene()'
test.cpp:(.text+0x192): undefined reference to `Scene::~Scene()'
test.cpp:(.text+0x1a1): undefined reference to `Sphere::~Sphere()'
test.cpp:(.text+0x1bf): undefined reference to `Scene::~Scene()'
test.cpp:(.text+0x1d3): undefined reference to `Sphere::~Sphere()'
生成文件:
CC = g++
SRC = ./src
BUILD = ./build
main : main.o Point.o colort.o Sphere.o Scene.o Ray.o HitRecord.o
$(CC) $(BUILD)/main.o $(BUILD)/Point.o -o $(BUILD)/main
main.o : $(SRC)/test.cpp
$(CC) -c $< -o $(BUILD)/main.o
Point.o : $(SRC)/Point.cpp $(SRC)/Point.h
$(CC) -c $< -o $(BUILD)/Point.o
colort.o : $(SRC)/colort.cpp $(SRC)/colort.h
$(CC) -c $< -o $(BUILD)/colort.o
Sphere.o : $(SRC)/Sphere.cpp $(SRC)/Sphere.h $(SRC)/colort.cpp $(SRC)/Point.cpp
$(CC) -c $< -o $(BUILD)/Sphere.o
ImagePlane.o : $(SRC)/ImagePlane.cpp $(SRC)/ImagePlane.h
$(CC) -c $< -o $(BUILD)/ImagePlane.o
Scene.o : $(SRC)/Scene.cpp $(SRC)/Scene.h
$(CC) -c $< -o $(BUILD)/Scene.o
Ray.o : $(SRC)/Ray.cpp $(SRC)/Ray.h
$(CC) -c $< -o $(BUILD)/Ray.o
HitRecord.o : $(SRC)/HitRecord.cpp $(SRC)/HitRecord.h
$(CC) -c $< -o $(BUILD)/HitRecord.o
clean :
rm $(BUILD)/*
test : main
$(BUILD)/main
Sphere.cpp:
#include "Sphere.h"
#include <math.h>
Sphere::Sphere() {
}
Sphere::~Sphere() {
}
...other class functions
#包括“Sphere.h”
#包括
球体::球体(){
}
球体::~Sphere(){
}
…其他类函数
在您的主规则中:
main : main.o Point.o colort.o Sphere.o Scene.o Ray.o HitRecord.o
$(CC) $(BUILD)/main.o $(BUILD)/Point.o -o $(BUILD)/main
请注意,尽管您提到Sphere.o是一个依赖项,但您并没有链接它。您还需要将其包含在生成行中:
main : main.o Point.o colort.o Sphere.o Scene.o Ray.o HitRecord.o
$(CC) $(BUILD)/main.o $(BUILD)/Point.o $(BUILD)/Sphere.o -o $(BUILD)/main
您可能还想添加其他项,因为您将它们列为依赖项。我在makefile的任何地方都看不到test.cpp
。你是怎么搞笑的?我忘了发了,现在还没找到问题;test.cpp什么时候编译?这就是生成错误消息的那个。@Pete它现在在那里,targetmain.o
OK@法塔莱罗已经给了你答案。看起来他们也需要Scene.o
。
main : main.o Point.o colort.o Sphere.o Scene.o Ray.o HitRecord.o
$(CC) $(BUILD)/main.o $(BUILD)/Point.o $(BUILD)/Sphere.o -o $(BUILD)/main