Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inlining class methods causes undefined reference

Tags:

c++

inline

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.

like image 726
FrankMN Avatar asked Jan 22 '11 17:01

FrankMN


People also ask

Can C++ compiler ignore inlining?

Remember: It is true that all the functions defined inside the class are implicitly inline and C++ compiler will perform inline call of these functions, but C++ compiler cannot perform inlining if the function is virtual. The reason is call to a virtual function is resolved at runtime instead of compile time.

What is code inlining?

Inlining is the process of replacing a subroutine or function call at the call site with the body of the subroutine or function being called. This eliminates call-linkage overhead and can expose significant optimization opportunities.

What is function inlining in C?

An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.


1 Answers

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?

like image 200
casablanca Avatar answered Sep 23 '22 11:09

casablanca