C vs. C++ on Embedded Devices
We wanted to avoid C++--since we lacked the space for both the
C and C++ standard libraries, choosing a C++ GUI would tie the entire
device to the C++ standard libraries. We had selected C libraries and
applications so we would have to compile in or add "glue"
code to ensure runtime compatibility with the C++ libraries. Doing this
would blend OO code with non-OO code and would increase the footprint.
Moreover, it is our experience that C is a better language than C++ for
small teams working on embedded devices. While in theory OOP with C++
lets you rearrange tasks into the most effective way to solve a problem,
in practice, C++ solutions are bulkier than their C counterparts.
- C++'s virtues are expensive. Advanced OOP
features,
such as templates and the practice of using classes in the place of
primitives, to name two examples, cause unacceptable code bloat.
- A C++ compiler may generate many routines for one
function (templates) or create routines where no function explicitly
appeared (constructors, casts, etc.). There is generally a one-to-one
relationship between a function in C code and the resulting machine-code
routine. It's easier to optimize what you can see than what you
must infer.
- Virtual methods and polymorphism complicate runtime
linking and require many relocations. This slows C++ application
launch time considerably. C applications are both simple to link and
amenable to lazy linking, so they load quickly. (For details, see Waldo
Bastian's paper ``Making C++ Ready for the Desktop",
http://www.suse.de/~bastian/Export/linking.txt.)
- Each class with virtual methods has an associated vtable
array, which adds memory overhead.
- C++'s tighter type-checking makes it difficult to
write the space-conscious code reuse common to C applications (think:
void *).
- The small, simple code demanded of embedded projects
provides maintainability. There is no reason to assume OOP will further
simplify such systems.
- GUIs may not have a simple solution in a rigorous
OOP model.
- It's easy to get carried away and start doing OOP
for OOP's sake. The One True Object Model may describe a problem
perfectly, but it comes at the cost of excessive code.
Carefully written C code can be much faster than C++ code,
especially on embedded hardware. GTK+'s hand-crafted object system
offers much better spatial locality than C++'s more numerous and
distributed constructors. Our device has a tiny cache, so locality is
an especially important performance consideration.