amoeba
amoeba

Reputation: 105

c++ class include undefined reference

I am having a problem constructing an instance of a class in a larger program.

In the main function I have:

//main.cpp
#include "MyClass.h"

MyClass aMyClass;
//do stuff with MyClass

MyClass' header is only a constructor at this point and looks like this:

//MyClass.h

class MyClass {
    public:
        MyClass();
};

MyClass' source then looks like this, again only a constructor at this point:

//MyClass.cpp
#include "MyClass.h"

//--CONSTRUCTOR--//
MyClass::MyClass(){
    cout << "constructing MyClass object..." << endl;
}

When I try to run my program I get this error:

undefined reference to `MyClass::MyClass()'
collect2: error: ld returned 1 exit status

Edit : I'm compiling the program with the following commands using the command line:

g++ main.cpp -o mainProgram

Edit (solved) : The compilation needs to include MyClass.cpp, the correct command is:

g++ man.cpp MyClass.cpp -o mainProgram

While I'm sure it's something small, where am I slipping up here? I've tried declaring the object earlier in the program, but that did not solve the problem and I got the same error.

Does anyone see a problem here?

Upvotes: 0

Views: 516

Answers (1)

egur
egur

Reputation: 7960

you also need to compile MyClass.cpp - that's where the implementation is.

g++ main.cpp MyClass.cpp -o mainProgram

Upvotes: 7

Related Questions