Go Down

Topic: __inline functions: undefined reference error (Read 1 time) previous topic - next topic

Mitch_CA

Jan 06, 2010, 05:24 am Last Edit: Jan 06, 2010, 05:25 am by mitch_79 Reason: 1
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: [Select]
#include "myClass.h"

myClass Instance;

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

void loop()
{
}


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


myClass.cpp
Code: [Select]
#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.

Mitch_CA

#1
Jan 06, 2010, 05:45 am Last Edit: Jan 06, 2010, 05:45 am by mitch_79 Reason: 1
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.

Coding Badly

#2
Jan 06, 2010, 07:22 am Last Edit: Jan 06, 2010, 07:23 am by bcook Reason: 1

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: [Select]
class myClass
{
 public:
   myClass();
   __inline void myFunction();
};

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

Mitch_CA

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

Go Up