by P.J. PLAUGER Embedded ++: An Overview

Is EC++ the diet pill that will shrink C++ down to size for embedded applications? Here’s P.J. Plauger’s take.

he Fall 1997 Embedded trary, I found growing enthusiasm on Systems Conference in several fronts. San Jose was a smashing success. Attendance was ■ The Embedded C++ Technical way up over last year, and Committee, a consortium of rather more than even the optimistic Japanese companies, held their Tprojections made by the Powers that third international meeting on Be before the conference opened. I September 30, across the street haven’t seen this much activity and from the convention center. About interest in the embedded marketplace 50 people showed up, many of them ever before. Period. vendors announcing new products Of particular interest to me was the that support this de facto industry attention awarded to Embedded C++. standard. Several major Japanese It was only a year earlier, at the Fall companies have also joined the 1996 Embedded Systems original four semiconductor heavy- Conference, that I had the honor of hitters as well P.J. Plauger is the author of the stan- formally introducing this project to ■ I repeated my talk on Embedded dard C++ library shipped with the public. It could have sunk without C++ on October 1 to an audience of Microsoft Visual C++. His “State of a trace in the intervening months— at least 150 people. There was obvi- the Art” column appears monthly in many optimistic new projects do— ous interest and lots of intelligent Embedded Systems Programming. but that didn’t happen. Quite the con- questions ■ Green Hills Software is now mar- Moving a C++ caught up. keting their embedded compiler It gets worse, at least from the stand- products with full EC++ support program between point of embedded systems program- ■ Metrowerks and Hiware, two other ming. Several of the new features add companies that license compilers significant overheads to a C++ pro- into the embedded marketplace, compilers has gram, in terms of both code size and announced their intention to supply execution speed. In some cases, the compilers that support Embedded become more overheads occur even if you don’t C++ in the near future explicitly make use of the new fea- ■ I talked to half a dozen exhibitors difficult, not less, tures. Customers aren’t asking for on the show floor who already knew these new features—at least, they about Embedded C++ and were haven’t yet been educated en masse to beginning to plan how to support it as a result of want the features—and the chip ven- for their customers dors haven’t gotten around to imple- standardization. menting all of them. Compiler devel- I’ll elaborate on these themes in the opment in the commercial world is dri- remainder of this article. But first, let ven by what customers are asking for me back up and supply a bit of history. All four companies shared a com- this month. There’s simply too many I can then fill in the relevant technical mon complaint. Their customers— things to do to devote product develop- details. (See also the sidebar, “Read almost all developers of embedded ment time in places that don’t confer All About It,” for a supplemental read- systems using their chips—were an immediate competitive advantage. ing list.) beginning to demand C++ compilers. Thus, some of the chip vendors Naturally, the vendors were eager to might love to have an excuse not to HISTORY oblige. All four companies offered have to supply, say, exception han- first heard of this project in some form of a C++ compiler, or were dling in C++. Many of their customers November 1995, while attending a about to. But when customers started would happily live without such a fea- meeting of WG21 and J16, the ISO using C++, they were largely dissatis- ture, at least for the more demanding Iand ANSI committees standardizing fied. They were accustomed to C, had embedded programming projects. And C++. Advanced Data Controls Corp. learned to deal with its complexities once the customers discover the over- (ADaC) is a Japanese company with over , and had heads associated with exception han- whom I’ve done business since their learned to accept its overheads. They dling, they may well want to avoid founding in 1982. My friends at ADaC were nevertheless surprised and those overheads even if the compiler urged me to extend my stay to attend a amazed at the added complexities and does support the feature. Equally, the Friday evening meeting they had overheads of C++. chip vendors don’t want to be stigma- arranged. Given the warmth and past On top of everything else was the tized. If the guy down the block sells a success of our business relationship, I dialect problem. C++ has been chang- compiler with some sexy feature, it’s didn’t hesitate to rearrange my travel ing rapidly and steadily for years. hard to make a case for not providing it plans and attend. “Standardization,” a process that nor- as well. Put simply, the vendors face a The meeting was astonishing. In mally stabilizes a programming lan- common software dilemma: how do addition to the folks from ADaC and a guage, began in 1989. But in the case you make sure that what the customers couple of fellow Americans, the atten- of C++, the standardization process think they want is also close to what dees included software people from the has been used as an opportunity to add they really need? four major Japanese semiconductor significant new capabilities to the lan- A popular solution to such a prob- manufacturers—Fujitsu, Hitachi, guage before it freezes. Multiple inher- lem is to define a suitable subset. In NEC, and Toshiba. These were the itance, exceptions, templates, and a this case, we’re talking about a subset folks responsible for providing soft- host of other major features have been of the full language and library man- ware development tools to their cus- added over the past seven years or so, dated by the draft C++ Standard. tomers. They were all wrestling with far faster than compiler writers can Include in the subset everything that what to do about C++, and they were keep up. As a consequence, every meets the need of embedded systems very frank about their problems. I have commercial C++ compiler implements programmers. Omit anything that personally never witnessed such an a different collection of language fea- arguably can be left out, either because open dialog between nominal competi- tures. Moving a C++ program between it adds to overheads, or it’s too new to tors, certainly not among American compilers has become more difficult, be widely available, or for some other companies. But then, we Americans not less, as a result of standardiza- good and proper reason. Get a bunch of enjoy a richer fabric of antitrust laws, tion—at least during this transitional people to agree on the subset. If sever- to keep companies from collaborating period before the draft C++ Standard al vendors supply the same subset, cus- unfairly. Or fairly, for that matter. finally settles down and everyone gets tomers can write C++ code that is both Embedded C++ efficient and portable across multiple Dr. Kiichiro Tamaru of Toshiba By September 1996, the Embedded implementations. Gone is much of the became vice secretary. ADaC is the C++ Technical Committee had pro- stigma for having less than a full secretariat. We Americans are merely duced a draft specification for their implementation. In its place is, in fact, advisers to the committee, which is subset. They even had a Web site up the cachet of matching a useful stan- very much a Japanese undertaking. and running. (See www.caravan.net/ dard, even if it’s only a de facto indus- The kickoff meeting was conducted ec2plus.) As I indicated earlier, I got to try standard. mostly in English, as a courtesy to us make the first public announcement at Thus was born the idea of Americans, who are notoriously weak the Fall 1996 Embedded Systems Embedded C++ (or EC++, for short) as at discussing technical matters in Conference. The project was out from a dialect aimed squarely at the needs of Japanese. Subsequent meetings were under wraps and into the marketplace. embedded systems programmers. The held in Japanese, rather more efficient- group that first came together that ly for the attendees I might add, THE EC++ LANGUAGE Friday night in Tokyo soon dubbed throughout much of 1996. The com- he Embedded C++ specification itself the Embedded C++ Technical mittee maintained a reflector, and did a is a proper subset of the full Committee. Hiroshi Monden of NEC heckuva lot of work between meetings, draft C++ Standard. Thus, the became chair of the committee, and in the bargain. Tmost economical way to describe it is READ ALL ABOUT IT often in terms of what it doesn’t have. I could list all the rules for writing dec- I’ve been writing about C++ and embedded systems for over five years now, both in larations, statements, and expressions, Embedded Systems Programming and in our sister publication, C/C++ Users Journal. For for instance. That might reassure peo- additional detail and considerably more background on the development of Embedded C++, ple who love detail that all the things you might want to review some of these essays. Most are available on CD-ROMs from they value about C++ (and C) are still Miller Freeman. there. But perspective is often lost in details. Saying what has been left out ■ “Embedded Programming in C++,” ESP, November 1992, p. 97—some early musings of EC++ is more economical, and often on the role of C++ in embedded systems programming more revealing. Rest assured that what ■ “Controlling Hardware from C and C++,” ESP, December 1992, p. 73—the basics of is left is a fully functional subset. low-level I/O in C, with some particular warnings about C++ issues Programming languages such as C ■ “An Embedded C++ Library,” ESP, October 1993, p. 113—how to adapt a hosted C++ and C++ make a fairly sharp distinc- library for embedded applications tion between “language” and “library.” ■ “From Indexes to Iterators,” ESP, July 1995, p. 125—evolution of the iterator concept The compiler is responsible for recog- as it now appears in the Standard Template Library (STL) nizing the language and generating ■ “A Taxonomy of Iterators,” ESP, August 1995, p. 101—description of the different cat- code that carries out its intent. The egories of iteratories used in STL library that accompanies the compiler ■ “Subsetting,” ESP, March 1996, p. 109—early warnings about the thinking behind some provides a grab bag of classes, func- of the EC++ effort, not yet announced tions, and objects likely to be of use in ■ “Figuring the Cost,” ESP, May 1996, p. 117—description of some of the hidden over- many programs. I begin here by dis- heads when programming in C++ cussing just the EC++ language. ■ “Gedankenware,” ESP, June 1996, p. 101—what happens to performance when you standardize before you acquire real-world experience ■ Multiple inheritance and virtual ■ “Too Much of a Good Thing,” ESP, July 1996, p. 93—ways to cut some of the worst base classes are omitted. These excesses of the draft Standard C++ library closely related features add quite a ■ “Embedded C++,” ESP, November 1996, p. 125—first formal announcement of the bit of complexity to the language, EC++ effort for a relatively small increase in ■ “Debugging Iterators,” ESP, February 1997, p. 92—ways to detect subtle programming expressiveness. Worse, they add errors when using STL overheads, however slight, to all ■ “Templates in C++,” ESP, October 1997, p. 169—overview of template technology in calls to virtual member functions. C++, and a few programming tricks (Have no fear, virtual member func- ■ “Developing the Standard C++ Library,” C/C++ Users Journal, October 1993, p. 10— tions are still present.) A compiler first of a long series on the draft Standard C++ library. Practically every monthly col- explicitly designed to recognize the umn from this one through the present is devoted to describing the draft Standard C++ EC++ dialect can eliminate these library. The columns between November 1995 and June 1997, in particular, are devot- overheads, if it chooses ed to the Standard Template Library ■ Runtime type identification (RTTI) ■ “Embedded C++,” C/C++ Users Journal, February 1997, p. 35—a progress report on is omitted. An even more recent the EC++ effort addition to C++ than multiple inher- itance, RTTI also adds complexity Embedded C++

for a relatively small payoff in effectively turns namespaces off. to just drop the feature from the expressiveness. Runtime overheads And the subtle effects of name- library. Thus, it’s hard to preserve the for RTTI tend to be small, but they spaces on already complex name Standard Template Library when there are present. As with multiple inher- lookup rules are still being discov- are no templates. My experience so far itance, such overheads can general- ered by implementors. This is is that this is the chunk most sorely ly be eliminated only if the compil- another good idea that may well be missed by programmers contemplating er has an EC++ dialect switch worth omitting from an embedded the use of EC++. But more on that ■ Exception handling is omitted. development environment topic later. Strong arguments can be advanced ■ New-style casts are omitted. This is The iostreams library, on the other both for keeping and omitting this a tougher call. The type cast opera- hand, began life in pre-standards days language feature. Code that throws tor has been in C almost since its as a collection of ordinary classes. The and catches exceptions can impose inception in the early ’70s. But classes became “templatized” a few useful structure on the generally many programmers will agree that it years ago, as part of a general conver- messy business of handling unusual needs to be refined. It sometimes sion of the library to make greater use conditions. But the space and time does too much, covering up pro- of templates. You can now traffic in overheads imposed on all programs gramming errors in the process. streams of “wide characters,” in order can be considerable, as you will Draft Standard C++ introduces four to support large character sets. You can soon see. Programmers of embed- new type cast operators to replace even presumably invent your own ded systems often prefer to turn off the old one, which is retained for kinds of streams. None of this latitude this machinery and use simpler, if backward compatability only. Of makes much sense in an embedded less well structured, mechanisms these, only the dynamic cast has environment, however, and the hidden instead added runtime overheads. I suspect overheads have proven to be enor- ■ Templates are omitted. Adding tem- the new-style casts were omitted mous. So, EC++ provides classes with plates arguably transformed C++ primarily on the basis of newness the traditional names istream, ostream, into a qualitatively different lan- and so forth. These classes are not retro guage. I’ve worked with templates Luckily for me, I was just an adviser artifacts, however. The EC++ enough to know that they are indeed to this effort. I can admire the design- iostreams classes behave just like their powerful and often well worth the ers for making tough decisions. At the counterparts in the draft Standard C++ added complexity. But they are still same time, I don’t have to take the heat library that are implemented as tem- a work in progress. The first com- for any controversial choices. It’s a plate specializations. mercial compilers that completely nice position to be in, for a change. You’ll find a similar treatment of the implement templates are just complex arithmetic classes. You can’t becoming available. Many products THE EC++ LIBRARY write the names complex and com- face years of development before ike the language portion, the plex in a language that doesn’t they fully catch up. Using templates Embedded C++ library is often support templates. Instead, EC++ pro- can also lead to surprising over- best described in terms of vides the classes float_complex and dou- heads. Change the type of one argu- Lwhat’s missing. Much of what has ble_complex with the same behavior. ment in one call to a template func- been omitted from the full draft This is one of the few places where tion and you can unwittingly double Standard C++ library must go out of EC++ is arguably not a pure proper the amount of code generated to necessity. Thus, there is no need for the subset of the full language and library. implement that function. Useful as header , which works hand A little more surprising is what’s left they are, templates are well worth in hand with the typeid operator to out of the Standard C library. The draft avoiding in an embedded context implement runtime type identification. Standard C++ library specification ■ Namespaces are omitted. They were Keeping the headers and “includes by reference” all of the added to C++ a few years ago as a is also hard to justify Standard C library, and then some. It kind of directory structure for the (though a case can still be made) if the mandates all the added support for wide global namespace. A principal language doesn’t support exception characters from Amendment 1 to the C intended use for namespaces was to handling. Standard. And it overloads a bunch of partition the Standard C++ library If the language doesn’t support tem- C functions in the bargain, to be more so that it could be selectively plates, then any library template class- in keeping with C++ usages. The EC++ replaced. But to date, I haven’t seen es or template functions perforce must library keeps the overloads, but it omits a design that achieves this goal. The disappear. In some cases, it makes all that extra baggage for supporting practical effect of adding name- sense to replace a template class with wide characters. Japanese developers spaces to C++ is to require pro- an ordinary class, or a template func- were the ones who championed this grammers to add a line to practical- tion with an ordinary function. But in addition to C—you’ think they’d be ly every existing C++ program that many cases, the only sensible thing is eager to keep it all. But the embedded Embedded C++ community has different needs. design of Embedded C++ is that a sub- programmers learn how to use the new Language and library support for wide set language can yield greater space stuff. But performance issues will con- characters is a luxury in this context. and speed efficiencies than the full tinue to be important for embedded For a more positive statement of C++ language. I’ve probably empha- systems for many years to come. what’s actually in the EC++ library, see sized too much the need to avoid new I wish I could present here a com- the sidebar, “EC++ Library Contents.” language features, out of kindness to prehensive list of benchmark results. implementors and programmers alike. My company, Dinkumware, Ltd., has PERFORMANCE That is a transient problem that should such a project under way, but it is still he proof of the pudding is in the cure itself over the next few years, as in the preliminary stages. What I can eating, as the saying goes. A the C++ Standard becomes official and present are some anecdotal results that fundamental premise behind the stable, compilers catch up with it, and I believe to be representative of actual T programming situations. They com- EC++ LIBRARY CONTENTS pare relative program sizes for a cou- ple of small test programs compiled in The Embedded C++ library is a subset of the C and C++ libraries mandated by the draft different ways and linked with differ- C++ Standard. Here is a brief synopsis of what’s required, on a header-by-header basis. ent libraries. The two libraries are the Dinkum ■ The header : functions is*, to* C++ Library and the Dinkum EC++ ■ The header : macros EDOM, ERANGE, errno Library. The former is a complete ■ The header : macros DBL_*, FLT_*, LDBL_* implementation of the draft Standard ■ The header : macros CHAR_BIT, *_MIN, *_MAX C++ library, in all its gory details. (See ■ The header : type lconv; function localeconv Microsoft VC++ v. 5.0 for an earlier ■ The header : macro HUGE_VAL; functions (overloaded on float, double, and long version of this library.) The evidence double) abs, acos, asin, atan, atan2, ceil, cos, cosh, exp, fabs, floor, fmod, frexp, ldexp, log, to date is that this is a particularly effi- log10, mod, pow, sin, sinh, sinh, sqrt, tan, tanh cient implementation, at least com- ■ The header : type jmp_buf; macro setjmp; function longjmp pared to the current competition. The ■ The header : type va_list; macros va_arg, va_end, va_start latter library is Dinkumware’s imple- ■ The header : macro offsetof; types ptrdiff_t, size_t mentation of the Embedded C++ ■ The header : types FILE, fpos_t, size_t; macros EOF, NULL; functions fclose, library. We also think it’s pretty effi- fflush, fgetc, fgetpos, fopen, fputc, fsetpos, getchar, gets, printf, putchar, puts, scanf, cient, but so far we have nothing to setvbuf, sprintf, sscanf, ungetc, vprintf, vsprintf; objects stdin, stdout compare it to. (See www.dinkumware. ■ The header : types div_t, ldiv_t; macros MB_CUR_MAX, RAND_MAX; functions abort, com for more information.) abs, atol, atof, atoi, bsearch, calloc, div, free, labs, ldiv, malloc, qsort, rand, realloc, Green Hills Software is a leading ven- srand, strtod, strtol, strtoul dor of compilers for the embedded mar- ■ The header : type size_t; macro NULL; functions memchr, memcmp, memcpy, memmove, ketplace. They license the Dinkumware memset, strcat, strchr, strcmp, strcpy, strcspn, strlen, strncat, strncmp, strncpy, strpbrk, libraries, in all flavors, for distribution strrchr, strspn, strstr, strtok with their compilers. The two test pro- ■ The header : types double_complex, float_complex; functions (overloaded on grams were compiled with their float_complex and double_complex) abs, arg, conjg, cos, cosh, exp, imag, log, log10, norm, PowerPC compiler that is now shipping. polar, pow, real, sin, sinh, sqrt, tan, tanh They generally observe that program ■ The header : types filebuf, ifstream, ofstream size and execution speed are directly ■ The header : manipulators resetiosflags, setbase, setfill, setiosflags, setpre- proportional, at least for typical test pro- cision, setw grams. My experience is that modern ■ The header : types ios, ios_base; manipulators boolalpha, dec, fixed, hex, internal, generally behave this left, noboolalpha, noshowbase, noshowpoint, noskipws, nouppercase, oct, right, scientific, way—execution time depends primarily showbase, showpoint, skipws, uppercase on the number of bytes of code the ■ The header : forward references to iostreams classes processor has to read. Barring hot spots, ■ The header : objects cin, cout this is proportional to the total program ■ The header : type istream; manipulators endl, ends, flush size. So I show here only relative pro- ■ The header : types new_handler, nothrow, nothrow_t; functions operator delete, oper- gram sizes. ator delete[], operator new, operator new[], set_new_handler A small program that makes simple ■ The header : type ostream; manipulator ws use of library I/O tends to be dominat- ■ The header : types istringstream, ostringstream, stringbuf ed by the contribution from the library. ■ The header : types fpos, streambuf, streamoff, streamsize The relative sizes of such a test pro- ■ The header : type string; function getline gram are: Embedded C++

■ 3 — EC++, no exceptions enormous, to the point that it inevitably C++ (ETC++) for the combined lan- ■ 5 — EC++ with exceptions compromises early attempts at econo- guage and library. Whatever the name, ■ 6 — Full C++, no exceptions my and/or simplicity. (Look at Java v. the dialect seems to be an effective ■ 8 — Full C++ with exceptions 1.1.) The Japanese committee mem- compromise between EC++ and full bers like their subset, and have so far C++. It retains the performance effi- Note first the dramatic savings that stuck by their guns, but they don’t ciencies of EC++, and offers the bene- occur when the compiler doesn’t have want to appear unresponsive. And they fits of STL. (Sorry if this sounds like a to worry about exception-handling recognize that other communities of sales pitch, but I’m genuinely enthusi- code. Your mileage may vary with your programmers may have a different mix astic about this dialect.) compiler, but exceptions are known to of needs than their chip customers. The last important consideration is exact a significant toll on code size Nobody wants a proliferation of political. Many people have labored and/or execution speed. Then note what dialects. The whole idea behind the for- many years to complete the draft C++ the simpler library gives you. By leav- mation of the consortium was to avoid Standard. Not the least among them is ing out unwanted machinery that can- such mayhem in the Japanese embed- Bjarne Stroustrup, the original author not be avoided in the full C++ library, ded systems community. Nevertheless, of C++. It’s hard to imagine these folks EC++ weighs in at about half the size. one significant new dialect has already would enjoy seeing their work sliced Combine the language and library sav- appeared. And it could become at least and diced by others even before the ink ings, and you get a program only three- as popular as EC++. dries on the draft. Everything that went eighths the size of full C++. Green Hills has a major customer into C++ during standardization went The effects are more dramatic for a who decided last year to adopt in for a reason. What right does some somewhat larger program that makes Embedded C++ as an internal standard other committee have to second guess greater demands on the library I/O for embedded projects. But they also all these difficult choices? facilities. In this case, it is harder for wanted to use the Standard Template In point of fact, there have been a the full C++ library to avoid loading Library. STL is a powerful tool with few grumblings. But Stroustrup him- great quantities of additional code. The the nice property that you don’t pay for self took the trouble to learn more relative sizes are: it if you don’t use it. (By contrast, the about the EC++ project and has been templatized iostreams in the full C++ gracious enough to give it his condi- ■ 3 — EC++, no exceptions library impose unavoidable overheads tional blessing. He freely recognizes ■ 5 — EC++ with exceptions on many programs.) So they got just the need for subsetting, to meet specif- ■ 30 — Full C++, no exceptions what they asked for. Dinkumware sup- ic goals. He makes it clear that he ■ 45 — Full C++ with exceptions plied the necessary hybrid library to never intended C++ to be so large or Green Hills, who in turn supplied the inefficient that it is unsuitable for pro- Yes, a program can truly weigh in at customer. gramming embedded systems. C++ only 1/15 the size of full C++. We were all pleasantly surprised to has a long tradition in that arena. Remember, we now live in a world discover that this was a happy combi- For embedded programming, where the traditional trivial program nation indeed. The EC++ library is Stroustrup favors the largest dialect of that simply prints “hello, world” can about one-fourth the size of the full C++ that avoids undue overheads. Thus, balloon to a full megabyte on some library. STL is about the same. So the he prefers to leave in any features that desktop implementations of C++. combined library is still only half the are “weightless”—that add no over- Typical savings may be less dramat- full library, but it offers most of the heads in space or speed. Namespaces ic, but the evidence to date is clear functionality that programmers seem and new-style casts are two obvious enough. There are indeed real perfor- to actually want today. Compilers have candidates for readmission, along with mance advantages to be had by pro- to be pretty up-to-date with the draft one or two other small items I’ve gramming with the EC++ subset lan- C++ Standard to support STL well, but glossed over. I think it’s fair to say that guage and library. that’s already not uncommon. Edison ETC++ meets his criteria pretty closely. Design Group (www.edg.com) supplies EC++ and ETC++ could benefit THE ETC++ DIALECT the C++ front end for many embedded from some refining. A few small don’t want to pretend that the story C++ compilers, and it is at the leading changes can simplify the business of ends here. For all the obvious suc- edge. It even has dialect switches moving a program between these two cess of Embedded C++ to date, a already installed for tailoring the rec- dialects and full C++. But these Ifew counter trends are inevitable. The ognized language to be EC++ or many dialects have already broadened the EC++ Technical Committee has faced other interesting variants. possibilities for programming embed- a steady stream of gripes because one Dinkumware calls this combination ded systems in C++. Given the broad or another valued feature has been of EC++ and STL the Dinkum range of applications that fall under omitted from the subset. The pressure Abridged Library. Green Hills has set- that umbrella term, we need all the to expand any specification can be tled on the name Embedded Template elasticity we can get. ■ This article appears with permission from EMBEDDED SYSTEMS PROGRAMMING, December 1997 ©1997 MILLER FREEMAN, INC. All Rights Reserved.