在 C++ 中包含标头时未定义引用
当我决定应该将其拆分为文件时,我正在处理我的项目。然而,我遇到了这样的问题,我通过谷歌找到的所有建议都是关于忘记链接我做对的两个对象文件(至少我认为是这样)。
Makefile:
test : class.o main.o
g++ class.o main.o -o test.exe
main.o : main.cpp
g++ main.cpp -c
class.o : class.cpp
g++ class.cpp -c
main.cpp
#include <iostream>
#include "class.h"
using namespace std;
int main() {
Trida * t = new Trida(4);
t->fce();
return 0;
}
class.h
#ifndef CLASS
#define CLASS
class Trida {
private:
int a;
public:
Trida(int n);
void fce();
};
#endif
class.cpp
#include <iostream>
using namespace std;
class Trida {
private:
int a;
public:
Trida(int n) {
this->a = n;
}
void fce() {
cout << this->a << endl;
}
};
错误消息:
gwynbleidd@gwynbleidd-pc:~/Skola/test$ make
g++ class.cpp -c
g++ main.cpp -c
g++ class.o main.o -o test.exe
main.o: In function `main':
main.cpp:(.text+0x26): undefined reference to `Trida::Trida(int)'
main.cpp:(.text+0x54): undefined reference to `Trida::fce()'
collect2: ld returned 1 exit status
make: *** [test] Error 1
I was working on my project while I decided that I should split it into files. However I got stucked with problem like this and all advice I found via google were about forgetting to link both object files which I am doing right (at least I think so).
Makefile:
test : class.o main.o
g++ class.o main.o -o test.exe
main.o : main.cpp
g++ main.cpp -c
class.o : class.cpp
g++ class.cpp -c
main.cpp
#include <iostream>
#include "class.h"
using namespace std;
int main() {
Trida * t = new Trida(4);
t->fce();
return 0;
}
class.h
#ifndef CLASS
#define CLASS
class Trida {
private:
int a;
public:
Trida(int n);
void fce();
};
#endif
class.cpp
#include <iostream>
using namespace std;
class Trida {
private:
int a;
public:
Trida(int n) {
this->a = n;
}
void fce() {
cout << this->a << endl;
}
};
Error message:
gwynbleidd@gwynbleidd-pc:~/Skola/test$ make
g++ class.cpp -c
g++ main.cpp -c
g++ class.o main.o -o test.exe
main.o: In function `main':
main.cpp:(.text+0x26): undefined reference to `Trida::Trida(int)'
main.cpp:(.text+0x54): undefined reference to `Trida::fce()'
collect2: ld returned 1 exit status
make: *** [test] Error 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所以这就是你做错的事情。在 class.cpp 中,您重新创建一个新 Trida 类,而不是实现您在 class.h 中创建的类。你的 class.cpp 应该看起来更像这样:
并且实际上你应该在构造函数中使用初始化而不是赋值:
So here's what you did wrong. In class.cpp you recreate a new Trida class rather than implement the one you've created in class.h. Your class.cpp should look more like this:
And really you should be using initialization rather than assignment in your constructor:
您定义了类
trida
两次(在头文件class.h
和源文件class.cpp
中)你的 class.cpp 文件应该是这样的
You are defining class
trida
two times (in the header fileclass.h
and in the source fileclass.cpp
)Your class.cpp file should be like