C++ inlining class methods causes undefined reference

Solution 1:

The body of an inline function needs to be in the header so that the compiler can actually substitute it wherever required. See this: How do you tell the compiler to make a member function inline?

Solution 2:

7.1.2/4 of the Standard:

An inline function shall be defined in every translation unit in which it is used...

You use TestMethod in main.cpp, but it's not defined there.

... If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required.

You define (and hence also declare) TestMethod inline in my_class.cpp, but not in main.cpp.

The fix in this case is to move the function definition to the header file, either like this:

class MyClass {
 public:
  void TestMethod() {}
};

or like this:

class MyClass {
 public:
  inline void TestMethod();
};

inline void MyClass::TestMethod() {}

Solution 3:

You've defined it as not inlined in the header file, while in the cpp file you're trying to define it as inline. That's a conflicted definition and it won't be able to find one from the other. Your header is where you really place the inline keyword.

However, I'd remove the inline keyword as it's really more of a suggestion to the compiler anyways. You really only need it when there's a free-floating function in the header and you don't want multiple definitions popping up in your code base.