C++ inlining class methods causes undefined reference

C++Inline

C++ Problem Overview


I'm getting a compiler error when I try to inline a method of one of my classes. It works when I take away the "inline" keyword.

Here's a simplified example:

main.cpp:

#include "my_class.h"

int main() {
  MyClass c;
  c.TestMethod();

  return 0;
}

my_class.h:

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

my_class.cpp:

#include "my_class.h"

inline void MyClass::TestMethod() {
}

I try compiling with:

g++ main.cpp my_class.cpp

I get the error:

main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'

Everything is fine if I take away the "inline". What's causing this problem? (and how should I inline class methods? Is it possible?)

Thanks.

C++ Solutions


Solution 1 - C++

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 - C++

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 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrankMNView Question on Stackoverflow
Solution 1 - C++casablancaView Answer on Stackoverflow
Solution 2 - C++Steve JessopView Answer on Stackoverflow
Solution 3 - C++wheatiesView Answer on Stackoverflow