Pages: [1]   Go Down
Author Topic: __inline functions: undefined reference error  (Read 931 times)
0 Members and 2 Guests are viewing this topic.
Waterloo, Canada
Offline Offline
Full Member
***
Karma: 1
Posts: 242
Engineer
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Please help me understand/eliminate this compiler error for an __inline member function for a class...

"In function 'setup':
C:\.../inlinefunction.cpp:10: undefined reference to `myClass::myFunction()'"

This is the code.
Sketch:
Code:
#include "myClass.h"

myClass Instance;

void setup()
{
    Instance.myFunction();
}

void loop()
{
}

myClass.h:
Code:
class myClass
{
  public:
    myClass();
    __inline void myFunction();
};

myClass.cpp
Code:
#include "myClass.h"

myClass::myClass()
{
  // constructor
}

__inline void myClass::myFunction()
{
  // nothing
}

Interestingly, if I push all the code together into the main sketch, it compiles successfully.  Only with the class defined in separate .cpp/.h files does it throw an error.
Alternately, if I maintain the file structure but remove the "__inline" declaration it also compiles successfully.
« Last Edit: January 05, 2010, 11:25:25 pm by mitch_79 » Logged

Waterloo, Canada
Offline Offline
Full Member
***
Karma: 1
Posts: 242
Engineer
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Well... if I declare the function in the .h file instead of the .cpp file it works.  But why it works when all text is contained in the same sketch is lost on me.
« Last Edit: January 05, 2010, 11:45:26 pm by mitch_79 » Logged

Global Moderator
Dallas
Online Online
Shannon Member
*****
Karma: 200
Posts: 12773
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset


For non-inline functions, code is generated for the function when the source file is compiled.  References (calls) to the function are resolved by the linker; it changes stubs in the referencing code to an actual call.

Code for inline functions is generated "on the spot".  Instead of a call, the code is inserted at the point of the call.  In order to insert the code when an inline function is "called", the compiler has to have access to the body of the function.

That isn't very well written so it probably doesn't make much sense.  Hopefully a concrete example will clear up the matter...

Moving the body for myFunction into the header file should resolve the problem...

myClass.h:
Code:
class myClass
{
  public:
    myClass();
    __inline void myFunction();
};
 
__inline void myClass::myFunction()
{
  // nothing
}
« Last Edit: January 06, 2010, 01:23:34 am by bcook » Logged

Waterloo, Canada
Offline Offline
Full Member
***
Karma: 1
Posts: 242
Engineer
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

That does explain it, and isn't poorly written at all.
Thank you.
Logged

Pages: [1]   Go Up
Jump to: