简体   繁体   中英

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.

Here's my code and the errors from the terminal:

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:

#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:

#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

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.

It is not enough to let the compiler know about your object by including Object.h from Main.cpp ; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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