我正在开发我的第一个大型 C++ 项目,但在正确构建它时遇到了巨大的问题。
首先,错误:
/tmp/ccn7hjru.o: In function `match(std::basic_istream<char, std::char_traits<char> >&, char const*)':
Geometry.cpp:(.text+0x0): multiple definition of `match(std::basic_istream<char, std::char_traits<char> >&, char const*)'
/tmp/ccfuS3Jb.o:Camera.cpp:(.text+0x0): first defined here
/tmp/ccn7hjru.o: In function `eat(std::basic_istream<char, std::char_traits<char> >&)':
Geometry.cpp:(.text+0xda): multiple definition of `eat(std::basic_istream<char, std::char_traits<char> >&)'
/tmp/ccfuS3Jb.o:Camera.cpp:(.text+0xda): first defined here
/tmp/ccIOhdcQ.o: In function `match(std::basic_istream<char, std::char_traits<char> >&, char const*)':
Light.cpp:(.text+0x0): multiple definition of `match(std::basic_istream<char, std::char_traits<char> >&, char const*)'
/tmp/ccfuS3Jb.o:Camera.cpp:(.text+0x0): first defined here
/tmp/ccIOhdcQ.o: In function `eat(std::basic_istream<char, std::char_traits<char> >&)':
Light.cpp:(.text+0xda): multiple definition of `eat(std::basic_istream<char, std::char_traits<char> >&)'
/tmp/ccfuS3Jb.o:Camera.cpp:(.text+0xda): first defined here
....
这持续了数百行
我所有的 c++ 课程文件如下所示:
#include "Camera.h"
#include "util.h"
Camera::Camera() {
// TODO Auto-generated constructor stub
}
Camera::Camera(int x, int y) {
this->resX = x;
this->resY = y;
}
Camera::~Camera() {
// TODO Auto-generated destructor stub
}
...more class methods below...
和头文件都看起来像这样:
#ifndef CAMERA_H_
#define CAMERA_H_
#include "SceneElement.h"
#include "P3D.h"
#include "Ray.h"
#define CAMERA_PRE "{CAM:"
#define CAMERA_POST ":CAM}"
#define TAG_LOCATION "LOC:"
#define TAG_PLANE "PLANE:"
#define TAG_UPPER_RIGHT "UR:"
#define TAG_UPPER_LEFT "UL:"
#define TAG_LOWER_RIGHT "LR:"
#define TAG_LOWER_LEFT "LL:"
#define TAG_RES_X "RESX:"
#define TAG_RES_Y "RESY:"
class Camera: public SceneElement {
public:
P3D location;
P3D upperLeft;
P3D upperRight;
P3D lowerLeft;
P3D lowerRight;
int resX, resY;
Camera();
Camera(int, int);
virtual ~Camera();
virtual void toStream(std::ostream &);
virtual void fromStream(std::istream &);
Ray getRay(int, int);
};
#endif /* CAMERA_H_ */
一个例外是一个 util 文件,它看起来像这样:
#include "util.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>
void match(std::istream &str, const char* expected){
int len = strlen(expected);
char* fromStream = (char*)malloc(len+1);
str.read(fromStream, len);
fromStream[len] = 0;
if(strcmp(fromStream, expected)){
std::cout << "expected " << expected << ", got " << fromStream << "\n";
free(fromStream);
exit(1);
}
free(fromStream);
}
void eat(std::istream &str){
char c;
while(c=str.peek(), c == ' ' || c == '\n' || c == '\t'){
str.get();
}
}
带有如下所示的头文件:
#ifndef UTILS
#define UTILS
#include <iostream>
void match(std::istream &str, const char* expected);
void eat(std::istream &str);
#endif