Thought Leadership

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.

Colin Walls

I have over thirty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles and two books on embedded software, I am a member of the marketing team of the Mentor Graphics Embedded Systems Division, and am based in the UK. Away from work, I have a wide range of interests including photography and trying to point my two daughters in the right direction in life. Learn more about Colin, including his go-to karaoke song and the best parts of being British: http://go.mentor.com/3_acv

More from this author

Comments

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

Leave a Reply

This article first appeared on the Siemens Digital Industries Software blog at https://blogs.stage.sw.siemens.com/embedded-software/2020/07/20/inline-c-code-in-embedded-applications/