The Person Here
The Person Here

Reputation: 520

Undefined reference to member function (C++)

I am using a Makefile to compile a C++ project, and I receive an undefined reference error which I suspect is for a simple mistake.

The error itself is:

$ make
g++ -c main.cpp
g++ -o p5 main.o
main.o:main.cpp:(.text+0x241): undefined reference to `Instructions::processInput(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: ld returned 1 exit status
Makefile:2: recipe for target `p5' failed
make: *** [p5] Error 1

Here are the parts of the project concerned with the error (for clarity's sake): My makefile:

p5: main.o Instructions.o
    g++ -o p5 main.o

main.o: main.cpp Instructions.h
    g++ -c main.cpp

Instructions.o: Instructions.h Instructions.cpp
    g++ -c Instructions.cpp

My main.cpp file:

#include <string>
#include "Instructions.h"
using namespace std;

int main() {
    Instructions inst;
    inst.processInput("some string par example"); //THIS LINE HERE GIVES ME ERRORS
    return 0;
}

My Instructions header file:

#ifndef INSTRUCTIONS_H
#define INSTRUCTIONS_H
#include <string>

class Instructions {
public:
    Instructions() {input = ""; command = 0; xCoord = 0.0; yCoord = 0.0;};
    void processInput(std::string in);
private:
    std::string input;
    int command;
    double xCoord;
    double yCoord;
};
#endif

And finally the .cpp file, very barebones at the moment:

#include "Instructions.h"
#include <string>
#include <iostream>
using namespace std;

void Instructions::processInput(string in) {
    cout << "Processing: " << input << endl;
}

I've been looking around for solutions but to no avail. Please excuse me then if it is indeed somewhere else! I also hope it helps all the beginners out there still coming to terms with C++!

Upvotes: 0

Views: 1731

Answers (1)

user813853
user813853

Reputation:

try this please Makefile :

 p5: Instructions.o main.o
     g++ Instructions.o main.o -o p5 

 Instructions.o: Instructions.cpp
     g++ -c Instructions.cpp -o Instructions.o 

 main.o: main.cpp Instructions.h
     g++ -c main.cpp Instructions.o -o main.o

to compile p5, you need first to compile all its dependencies which is Instructions.o and main.o. Instructions.o is independent, so it can be compiled like this g++ -c Instructions.cpp. But main.o depend on the class Instructions so it depend on its .o It should be compiled like this g++ -c main.cpp Instructions.o.

Same thing for p5, it needs all the *.o.

Upvotes: 2

Related Questions