简体   繁体   English

我收到“未定义的引用”错误,我不明白为什么(C ++ OO)

[英]I'm getting “undefined reference” errors and I don't understand why (C++ OO)

I've looked at multiple other posts on undefined reference errors, but I can't see any errors in my code. 我看过其他许多关于未定义参考错误的文章,但是我的代码中看不到任何错误。 Is there something I'm not catching? 有什么我没捉到的吗? I'm compiling with g++ in the ubuntu command line. 我正在ubuntu命令行中使用g ++进行编译。

Here's my code and the errors from the terminal: 这是我的代码以及来自终端的错误:

Main.cpp: Main.cpp:

#include <iostream>
#include "Object.h"

using namespace std;


int main(){
    Object* o = new Object(3,6,9);
    o->printVolume();
    delete o;
    return 0;
}

Object.h: Object.h:

#ifndef OBJECT_H_
#define OBJECT_H_

class Object
{
public:
    Object(double xSize, double ySize, double zSize);   
    ~Object();
    void printVolume();
private:
    double x,y,z;
};

#endif

Object.cpp: Object.cpp:

#include <iostream>
#include "Object.h"


using namespace std;

Object::Object(double xSize, double ySize, double zSize){
    x = xSize;
    y = ySize;
    z = zSize;
}

Object::~Object(){
    cout << "Object destroyed." << endl;
}

void Object::printVolume(){
    cout << x * y * z << endl;
}

Errors: 错误:

/tmp/ccUeuPTn.o: In function main': Main.cpp:(.text+0x47): undefined reference to Object::Object(double, double, double)' Main.cpp:(.text+0x57): undefined reference to Object::printVolume()' Main.cpp:(.text+0x68): undefined reference to Object::~Object()' collect2: error: ld returned 1 exit status /tmp/ccUeuPTn.o:在函数main': Main.cpp:(.text+0x47): undefined reference to Object :: Object(double,double,double)的main': Main.cpp:(.text+0x47): undefined reference to Main.cpp :(。text + 0x57):未定义对Object::printVolume()' Main.cpp:(.text+0x68): undefined reference to引用Object::printVolume()' Main.cpp:(.text+0x68): undefined reference toObject::printVolume()' Main.cpp:(.text+0x68): undefined reference to collect2:错误:ld返回1退出状态

Is there something that I'm missing? 有什么我想念的吗?

Compilation appears to have succeeded, and these errors appear to be produced by the linker (or some other kind of post-compilation step) and they are telling you that your Object::Object(double xSize, double ySize, double zSize) constructor is nowhere to be found. 编译似乎已成功,并且这些错误似乎是由链接器(或其他某种后编译步骤)产生的,并且它们告诉您Object::Object(double xSize, double ySize, double zSize)构造函数是无处可寻。

It is not enough to let the compiler know about your object by including Object.h from Main.cpp ; 仅通过包含Main.cpp Object.h来让编译器知道您的对象是不够的; this will cause compilation to succeed, but it is only half the story. 这将使编译成功,但这只是故事的一半。

The other half of the story is that linking must also succeed, so you have to somehow make Object.o available to Main.o during linking. 故事的另一半是连接也必须成功,所以你必须以某种方式使Object.o提供给Main.o链接过程中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM