On Sun, May 29, 2011 at 11:12:09PM -0400, Gene Smith wrote: > > > >I really wonder about the logic behind the use of C++ in small embedded > >devices. > > > > I agree. But sometimes it is decreed on high that you will use c++ > and so and so's c++ library code. :( At RTSI, we've been using C++ in embedded systems of all sizes, from 32k ROM on up, for about 15 years now. We've found major advantages over C in code quality and reuseability. Many things you _should_ be doing in C to make your code correct, robust, and maintainable are directly supported in C++: - Encapsulation: limiting the scope over which names can be seen, and enforcing access restrictions to data and code (like C file-static data and functions, but more powerful) - Inheritance: supporting re-use of common data structures and algorithms without copy-paste coding (like nested structures in C) - Polymorphism (virtual functions): allowing common code to vary its operation based on the situation (like C callbacks, but built into the language) - Generics (templates): supporting algorithms that can work on many different data types (replaces C macro functions, but type-safe). It is true, of course, that not every big-system practice is appropriate for embedded systems. For example, the usual approach of layering iostreams over stdio is over-complex. Instead, at RTSI we simply derive our serial port drivers directly from class streambuf, so we then can use istreams and ostreams to perform parsing and formatting: class UartBuf : public streambuf { // ... // override the required streambuf virtual functions: virtual int overflow(int); virtual int underflow(); // ... }; void main() { UartBuf uartBuf(/* port address, baud rate, etc */); ostream os(uartBuf); os << "Hello, world!" << endl; } This technique also works well for things like TCP connections. C++ is definitely a more sophisticated language than C; it took me some considerable time to become truly proficient in it. Written properly, a C++ program generates no more code (and in some cases less code) than the corresponding C program, but the C++ program can be shorter, clearer, more likely correct, and more robust under maintenance. On our website are a couple of articles showing how we use C++ for embedded control: http://www.realtime.bc.ca/articles Regards, David Querbach Real-Time Systems Inc.
Attachment:
signature.asc
Description: Digital signature