Inline C++ code in embedded applications

One of the key differences between coding for an embedded system or for a desktop computer is compiler optimization. For a desktop application, the priority is almost always speed, as memory is, in effect, unlimited. Embedded code needs to be tuned to the requirements of a specific device; it might be speed, but it could be memory size or even other factors. Control is the key thing. The embedded developer needs to know how to set up the compiler and use the programming language to achieve their goals.

A common optimization for speed is inlining code …

Inlining is the process of inserting a copy of a function’s actual code instead of each call to that function. This speeds up the execution as the cal/return sequence is eliminated. Stack usage is also reduced. However, overall code size is increased. It is a trade-off. Clearly, smaller functions provide the best benefits.

A good C/C++ compiler should inline smaller functions, if it is set to produce fast code. C++ has always had an inline keyword and this was introduced more recently into C. This is a hint to the compiler that a function might be inlined. It is used like this:

inline void fun()
{
}

In C++ there is another way to pass this hint to the compiler, specifically for class member functions [methods]. You can create a class like this:

class myclass
{
public:
   void memfun()
   {
   }
};

By including the code for memfun() inside the class definition, you give the inlining hint to the compiler. This produces exactly the same results as:

class myclass
{
public:
   void memfun();
};

inline void myclass::memfun()
{
}

Which style you select is a personal choice. Maybe the second is best if the class definition is quite complex.

Comments

2 thoughts on “Inline C++ code in embedded applications

Leave a Reply