To write a bootloader in C or C++?

waffleman picture waffleman · Oct 27, 2009 · Viewed 7.5k times · Source

I am writing a program, more specifically a bootloader, for an embedded system. I am going to use a C library to interact with some of the hardware components and I have the choice of writing it either in C or C++. Is there any reason I should choose one over the other? I do not need the object oriented features of C++ but it does have a stronger type system. Could it have other language features that would make the program more robust? I know some people avoid C++ because it can (but not always) generate large firmware images.

Answer

DrAl picture DrAl · Oct 27, 2009

This isn't a particularly straightforward question to answer. It depends on a number of factors including:

  • How you prefer to layout your code.
  • Whether there's a C++ compiler available for your target (and any other targets you may wish to use the bootloader on).
  • How critical the code size is for your application (we're talking about 10% extra maybe, not MB as suggested by another answer).

Personally, I really like classes as a way of laying out my code. Even when writing C code, I'll tend to keep everything in modular files with file-scope static functions "simulating" member functions and (a few) file-scope static variables to "simulate" member variables. Having said that, most of my existing embedded projects (all of which are relatively small scale, up to a maximum of 128kB flash including bootloader, but usually less) have tended to be written in C. Now that I have a C++ compiler though, I'm certainly considering moving to C++.

There are considerable benefits to C++ from simply using references, overloading and templates, even if you don't go as far as classes. Certainly, I'd stop short of using a lot of more advanced features, including the use of dynamic memory allocation (new). Then again, I'd avoid dynamic memory allocation (malloc etc) in embedded C as well if possible.

If you have a C++ compiler (even if it's only g++), it is worth running your code through it just for the additional type checking so that you can reduce the number of problems in your code. The C++ compiler can pick up on a few things that even static analysis tools won't spot.

For a good discussion on many invalid reasons people reject C++, see Dan Saks' article on Embedded.com.