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.
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.
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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With