user3193812
user3193812

Reputation: 11

Undefined reference to class methods

I have three files method.h,method.cpp,main.cpp

method.h

#ifndef METHOD_H
#define METHOD_H

class method {

public:
       void printThisMethod();
private:

};

#endif

method.cpp

#include "method.h"
inline void method::printThisMethod() {
    //some methods done here
}

main.cpp

 #include <iostream>
 #include <string>
 #include "method.h"

 int main() {
     method outputMethod;
     outputMethod.printThisMethod;
 }

I am getting the error,

undefined reference to method::printThisMethod.

Please help thanks

Upvotes: 1

Views: 196

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254751

Either remove the inline keyword, or move the definition into the header (keeping the inline).

inline is used to relax the One Definition Rule to allow definitions in headers. However, it also requires a definition in every translation unit that uses it, which often requires the definition to be in a header.

Without inline, normal linkage rules apply, and there must be a single definition in one translation unit. That is what you'll have, if you remove inline from your existing code.

(You also need to add parentheses to the function call, outputMethod.printThisMethod(), but presumably your real code has them, otherwise it wouldn't get as far as the link error.)

Upvotes: 3

tillaert
tillaert

Reputation: 1835

You need to change

outputMethod.printThisMethod;

to

outputMethod.printThisMethod();

Upvotes: 0

Related Questions