2015/03/08

Using C++ in embedded environments

Although C++ is an incredible language, its use in constrained embedded environments is not much common. Somewhat surprisingly, even engineers with a good background of C++ in mid-size environments (e.g. Linux capable systems) often resort to plain old C when they work in small systems like an AVR. I believe there is more tradition than reason to this, and I will try to explain my reasons in this article.



The main argument I've heard against using C++ is about speed. People say that C++ does too much stuff behind the scenes and thus causes an increase in code size and a speed reduction. This is, however, a misunderstanding. C++ features like virtual methods do have a performance cost, but you would pay that cost in C too if you tried to write the same functionality (for example using tables of function pointers). Moreover, letting the compiler do that job for you has two main advantages. First, it lets you free to focus on the problem you are dealing with, not with the language itself. Second, if the compiler can optimize it out, it will. As a result you usually have better, faster code and less troubles in general.

Most other critics go for templates. It should suffice to say, that templates are not mandatory in C++ (just like all other features, anyway), so if you don't use them, they can't hurt performance at all. But besides that, template code is not really slower. Modern compilers identify identical copies of the code and avoid duplication during the linking phase.  In fact, in C++ you can do a lot of metaprogramming with templates, and solve computations in compile time! This makes some code even faster than anything you can get in plain C.

Even if you can't take advantage of metaprogramming for your project, templates allow deeper integration between different parts of the code, leading to further optimizations that couldn't happen in C. For a good example, see Bjarne Stroustrup's talk on std::sort vs qsort.

But the very most important point I want to make is not about performance. Development in embedded environments is usually limited by the scarce tools you are able to use. Debugging is cumbersome, and our diagnostics methods seem primitive when compared to desktop environments.
Under such circumstanes, I believe it is vital to have a language that helps you as much as possible in preventing bugs. Proper type safety, consts vs defines, encapsulation of code in classes and namespaces and reduction in code duplicity by means of templates are great tools to help you create a better, more readable and maintainable code that will save you hours of work.

Give it a try, embrace the modern world of C++ on small micros and your life will become easier.

No comments:

Post a Comment