<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>State Space</title>
	<atom:link href="http://embeddedgurus.com/state-space/feed/" rel="self" type="application/rss+xml" />
	<link>http://embeddedgurus.com/state-space</link>
	<description>A Blog by Miro Samek</description>
	<lastBuildDate>Tue, 27 Apr 2010 23:12:27 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>RTOS without blocking?</title>
		<link>http://embeddedgurus.com/state-space/2010/04/rtos-without-blocking/</link>
		<comments>http://embeddedgurus.com/state-space/2010/04/rtos-without-blocking/#comments</comments>
		<pubDate>Mon, 19 Apr 2010 18:13:55 +0000</pubDate>
		<dc:creator>Miro Samek</dc:creator>
				<category><![CDATA[RTOS Multithreading]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/?p=40</guid>
		<description><![CDATA[In my previous post, &#8220;I hate RTOSes&#8221;, I have identified blocking as the main cause of the particular brittleness and inflexibility of the programs based on RTOSes. Here I&#8217;d like to discuss techniques of minimizing blocking and eradicating it completely from the application-level code. In other words, I&#8217;d like to show you how to use [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous post, &#8220;I hate RTOSes&#8221;, I have identified blocking as the main cause of the particular brittleness and inflexibility of the programs based on RTOSes. Here I&#8217;d like to discuss techniques of minimizing blocking and eradicating it completely from the application-level code. In other words, I&#8217;d like to show you how to use an RTOS for building responsive event-driven software.</p>
<p>For reasons I&#8217;ve outlined before, experienced RTOS users have learned to be weary of peppering the code with the blocking calls to the RTOS. So, even though every RTOS boasts a plethora of various communication and synchronization mechanisms (all of them based on blocking), advanced real-time developers intentionally limit their designs to just one generic blocking call per task, as shown in the following pseudocode:</p>
<pre>void task_routine(void *arg) {
    while (1) {
        // block on any event designated for this task (generic)
        // process the event *without* further blocking (task specific)
    }
}
</pre>
<p>Most RTOSes provide mechanisms to wait for <strong>multiple</strong> events in a single blocking call, for example: event flags, message mailboxes, message queues, the <code>select()</code> call, condition variables, and many others. From all these possibilities, I&#8217;d like to single out the message queue, because it is the most generic and flexible mechanism. A message posted to a message queue not only unblocks any task that waits on the queue (synchronization), but the message can also contain any information associated with the event (interprocess communication). For example, a message from an analog-to-digital converter (ADC) can signal when the conversion has completed as well as the actual value of the conversion result.</p>
<p>The generic pseudocode of a task based on a message queue looks as follows:</p>
<pre>void task_routine(void *arg) {
    while (1) { // main event loop of the task
        void *event = msg_queue_get(); // wait for event
        // process the event *without* further blocking (task specific)
    }
}
</pre>
<p>The most important premise of this <strong>event-loop</strong> design is that the task-specific code that processes the events obtained from the queue is <strong>not</strong> allowed to block. The event-processing code must execute quickly and return back to the event loop, so that the event loop can check for other events.</p>
<p>This design also automatically guarantees that each event is processed in <strong>run-to-completion</strong> (RTC) fashion. By design, the event loop must necessarily complete processing of the current event before looping back to obtain and process the next event. Also note that the need for queuing events is an immediate consequence of the RTC processing style. Queuing prevents losing events that arrive while the event-loop is executing an RTC step.</p>
<p>The event-loop pseudocode shown above is still task-specific, but it is quite easy to make it completely generic. As shown below, you can combine a message queue and an event-handler pointer-to-function in the TCB structure. A pointer to the TCB struct can be then passed to the task in the argument of the task routine (<code>arg</code>). This is quite easily achieved when the task is created.</p>
<pre>typedef struct {
    MessageQueue queue;        // event queue associated with the task
    void (*handler)(void *event); // event handler pointer-to-function
} TCB;   // task control block

void task_routine(void *arg) {
    while (1) { // main event loop of the task
        void *event = msg_queue_get(((TCB *)arg)-&gt;queue); // wait for event
        (*((TCB *)arg)-&gt;handler)(event);// handle the event without blocking
    }
}
</pre>
<p>The last snippet of code is generic, meaning that this simple event-loop can be used for <strong>all</strong> tasks in you application. So at this point, you can consider the <code>task_routine()</code> function as part of the generic event-driven infrastructure for executing your applications, which consist of event-handler functions.</p>
<p>What this way of thinking gives you is quite significant, because in fact you have just created your first event-driven <strong>framework</strong>.</p>
<p>The distinction between a framework and a toolkit is simple. A toolkit, such as an RTOS, is essentially a collection of functions that <strong>you</strong> can call. When you use a toolkit, <strong>you</strong> write the main body of the application (such as all the task routines) and <strong>you</strong> call the various functions from the RTOS. When you use a framework, you reuse the main body (such as the <code>task_routine()</code> function) and you provide the code that <strong>the framework</strong> calls. In other words, a framework uses <strong>inverted</strong> control compared to a traditional RTOS.</p>
<p>Inversion of control is a very common phenomenon in all event-driven architectures, because it recolonizes the plain fact that the events are controlling the application, not the other way around.</p>
<p>In my next post in the &#8220;I hate RTOSes&#8221; series, I&#8217;ll talk about challenges of programming without blocking. I&#8217;ll explain what you need to sacrifice when you write non-blocking code and why this often leads to &#8220;spaghetti&#8221; code. Stay tuned!</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2010/04/rtos-without-blocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>I hate RTOSes</title>
		<link>http://embeddedgurus.com/state-space/2010/04/i-hate-rtoses/</link>
		<comments>http://embeddedgurus.com/state-space/2010/04/i-hate-rtoses/#comments</comments>
		<pubDate>Mon, 12 Apr 2010 18:22:16 +0000</pubDate>
		<dc:creator>Miro Samek</dc:creator>
				<category><![CDATA[Firmware Bugs]]></category>
		<category><![CDATA[RTOS Multithreading]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/?p=35</guid>
		<description><![CDATA[I have to confess that I&#8217;ve been experiencing a severe writer&#8217;s block lately. It&#8217;s not that I&#8217;m short of subjects to talk about, but I&#8217;m getting tired of circling around the most important issues that matter to me most and should matter the most to any embedded software developer. I mean the basic software structure.
Unfortunately, [...]]]></description>
			<content:encoded><![CDATA[<p>I have to confess that I&#8217;ve been experiencing a severe writer&#8217;s block lately. It&#8217;s not that I&#8217;m short of subjects to talk about, but I&#8217;m getting tired of circling around the most important issues that matter to me most and should matter the most to any embedded software developer. I mean the basic software structure.</p>
<p>Unfortunately, I find it impossible to talk about truly important issues without stepping on somebody&#8217;s toes, which means picking a fight. So, in this installment I decided to come out of the closet and say it openly: I hate RTOSes.</p>
<p>The main reason I say so is because a conventional RTOS implies a certain programming paradigm, which leads to particularly brittle designs. I&#8217;m talking about blocking. Blocking occurs any time you wait explicitly in-line for something to happen. All RTOSes provide an assortment of blocking mechanisms, such as various semaphores, event-flags, mailboxes, message queues, and so on. Every RTOS task, structured as an endless loop, must use at least one such blocking mechanism, or else it will take all the CPU cycles. Typically, however, tasks block in many places scattered throughout various functions called from the task routine (the endless loop). For example, a task can block and wait for a semaphore that indicates end of an ADC conversion. In other part of the code, the same task might wait for a timeout event flag, and so on.</p>
<p>Blocking is evil, because it appears to work initially, but quickly degenerates into a unmanageable mess. The problem is that while a task is blocked, the task is not doing any other work and is not responsive to other events. Such task cannot be easily extended to handle other events, not just because the system is unresponsive, but also due to the fact the the whole structure of the code past the blocking call is designed to handle only the event that it was explicitly waiting for.</p>
<p>You might think that difficulty of adding new features (events and behaviors) to such designs is only important later, when the original software is maintained or reused for the next similar project. I disagree. Flexibility is vital from day one. Any application of nontrivial complexity is developed over time by gradually adding new events and behaviors. The inflexibility prevents an application to grow that way, so the design degenerates in the process known as architectural decay. This in turn makes it often impossible to even finish the original application, let alone maintain it.</p>
<p>The mechanisms of architectural decay of RTOS-based applications are manifold, but perhaps the worst is unnecessary proliferation of tasks. Designers, unable to add new events to unresponsive tasks are forced to create new tasks, regardless of coupling and cohesion. Often the new feature uses the same data as other feature in another tasks (we call such features cohesive). But placing the new feature in a different task requires very careful sharing of the common data. So mutexes and other such mechanisms must be applied. The designer ends up spending most of the time not on the feature at hand, but on managing subtle, hairy, unintended side-effects.</p>
<p>For decades embedded engineers were taught to believe that the only two alternatives for structuring embedded software are a &#8220;superloop&#8221; (main+ISRs) or an RTOS. But this is of course not true. Other alternatives exist, specifically event-driven programming with modern state machines is a much better way. It is not a silver bullet, of course, but after having used this method extensively for over a decade I will never go back to a raw RTOS. I plan to write more about this better way, why it is better and where it is still weak. Stay tuned.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2010/04/i-hate-rtoses/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Free store is not free lunch</title>
		<link>http://embeddedgurus.com/state-space/2010/01/free-store-is-not-free-lunch/</link>
		<comments>http://embeddedgurus.com/state-space/2010/01/free-store-is-not-free-lunch/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 19:27:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Coding Standards]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2010/01/29/free-store-is-not-free-lunch/</guid>
		<description><![CDATA[In my previous post &#8220;A Heap of Problems&#8221; I have compiled a list of problems the free store (heap) can cause in real-time embedded (RTE) systems. This was quite a litany, although I didn’t even touch the more subtle problems yet (for example, the C++ exception handling mechanism can cause memory leaks when a thrown [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous post &#8220;<a href="http://www.embeddedgurus.net/state-space/2010/01/heap-of-problems.html">A Heap of Problems</a>&#8221; I have compiled a list of problems the free store (heap) can cause in real-time embedded (RTE) systems. This was quite a litany, although I didn’t even touch the more subtle problems yet (for example, the C++ exception handling mechanism can cause memory leaks when a thrown exception bypasses memory de-allocation).</p>
<p>But even though the free store is definitely not a free lunch, getting by without the heap is certainly easier said than done. In C, you will have to rethink implementations that use lists, trees, and other dynamic data structures. You’ll also have to severely limit your choice of the third-party libraries and legacy code you want to reuse (especially if you borrow code designed for the desktop). In C++, the implications are even more serious because the object-oriented nature of C++ applications results in much more intensive dynamic-memory use than in applications using procedural techniques. For example, most standard C++ libraries (e.g., STL, Boost, etc.) requrie the heap. Without it, C++ simply does not feel like the same language.</p>
<p>Here are a few common sense guidelines for dealing with the heap:</p>
<p>1. For smaller systems, such as microcontrollers with only on-chip RAM, you probably don&#8217;t want to open the heap can of worms at all. The problems and waste that goes with the heap aren&#8217;t simply worth the trouble.</p>
<p>For systems with sufficient RAM, such as processors with megabytes of external DRAM, trading some of this cheap RAM for convenience in programming might be a reasonable deal. In the following discussion I assume that the system is big enough to run under a preemptive RTOS.</p>
<p>2. The simplest option is to limit the use of the heap to just one task. In this case, heap is not being shared concurrently and does not need any mutual-exclusion protection mechanism. To limit the non-determinism of the heap, I would recommend assigning low priority to the task that uses the heap. The priority should be lower than any real-time task.</p>
<p>3. At the expense of introducing a mutual protection to *all* heap operations (e.g., a mutex), you can allow more than one task to use the heap. However, I would still strongly recommend against using the heap in any tasks with real-time deadlines. All tasks that use the heap should run at a lower priority than any of the real-time tasks.</p>
<p>4. In any case, heap should never be used inside the interrupt service routines (ISRs).</p>
<p>In summary, using the heap in real-time embedded (RTE) systems always requires extra thought and discipline. You should always make sure that the heap is correctly integrated with your runtime environment.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2010/01/free-store-is-not-free-lunch/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A Heap of Problems</title>
		<link>http://embeddedgurus.com/state-space/2010/01/heap-of-problems/</link>
		<comments>http://embeddedgurus.com/state-space/2010/01/heap-of-problems/#comments</comments>
		<pubDate>Sun, 24 Jan 2010 22:24:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2010/01/24/a-heap-of-problems/</guid>
		<description><![CDATA[Some design problems never seem to go away. You think that anybody who has been in the embedded software development business for a while must have learned to be wary of malloc() and free() (or their C++ counterparts new and delete). Then you find that many developers actually don&#8217;t know why embedded real-time systems are [...]]]></description>
			<content:encoded><![CDATA[<p>Some design problems never seem to go away. You think that anybody who has been in the embedded software development business for a while must have learned to be wary of malloc() and free() (or their C++ counterparts new and delete). Then you find that many developers actually don&#8217;t know why embedded real-time systems are so particularly intolerant of heap problems.</p>
<p>For example, recently an Embedded.com reader attacked my comment to the article &#8220;<a href="http://www.embedded.com/design/opensource/216800007">Back to the Basics &#8211; Practical Embedded Coding Tips: Part 1 Reentrancy, atomic variables and recursion</a>&#8220;, in which I advised against using the heap. Here is this reader&#8217;s argumentation:</p>
<blockquote><p>I have no idea why did you bring up the pledge not to use the heap, on modern 32-bit MCUs (ARMs etc) there is no reason &#8211; and no justification &#8211; to avoid using the heap. The only reason not to use the heap is to avoid memory fragmentation, but good heap implementation and careful memory allocation planning will overcome that.</p></blockquote>
<p>As I cannot disagree more with the statements above, I decided that it&#8217;s perhaps the time to re-post my &#8220;heap of problems&#8221; list, which goes as follows:</p>
<ul>
<li>Dynamically allocating and freeing memory can fragment the heap over time to the point that the program crashes because of an inability to allocate more RAM. The total remaining heap storage might be more than adequate, but no single piece satisfies a specific malloc() request.</li>
<li>Heap-based memory management is wasteful. All heap management algorithms must maintain some form of header information for each block allocated. At the very least, this information includes the size of the block. For example, if the header causes a four-byte overhead, then a four-byte allocation requires at least eight bytes, so only 50 percent of the allocated memory is usable to the application. Because of these overheads and the aforementioned fragmentation, determining the minimum size of the heap is difficult. Even if you were to know the worst-case mix of objects simultaneously allocated on the heap (which you typically don&#8217;t), the required heap storage is much more than a simple sum of the object sizes. As a result, the only practical way to make the heap more reliable is to massively oversize it.</li>
<li>Both malloc() and free() can be (and often are) nondeterministic, meaning that they potentially can take a long (hard to quantify) time to execute, which conflicts squarely with real-time constraints. Although many RTOSs have heap management algorithms with bounded, or even deterministic performance, they don&#8217;t necessarily handle multiple small allocations efficiently.</li>
</ul>
<p>Unfortunately, the list of heap problems doesn&#8217;t stop there. A new class of problems appears when you use heap in a multithreaded environment. The heap becomes a shared resource and consequently causes all the headaches associated with resource sharing, so the list goes on:</p>
<ul>
<li>Both malloc() and free() can be (and often are) non-reentrant; that is, they cannot be safely called simultaneously from multiple threads of execution.</li>
<li>The reentrancy problem can be remedied by protecting malloc(), free(), realloc(), and so on internally with a mutex, which lets only one thread at a time access the shared heap. However, this scheme could cause excessive blocking of threads (especially if memory management is nondeterministic) and can significantly reduce parallelism. Mutexes can also be subject to priority inversion. Naturally, the heap management functions protected by a mutex are not available to interrupt service routines (ISRs) because ISRs cannot block.</li>
</ul>
<p>Finally, all the problems listed previously come on top of the usual pitfalls associated with dynamic memory allocation. For completeness, I&#8217;ll mention them here as well.</p>
<ul>
<li>If you destroy all pointers to an object and fail to free it or you simply leave objects lying about well past their useful lifetimes, you create a memory leak. If you leak enough memory, your storage allocation eventually fails.</li>
<li>Conversely, if you free a heap object but the rest of the program still believes that pointers to the object remain valid, you have created dangling pointers. If you dereference such a dangling pointer to access the recycled object (which by that time might be already allocated to somebody else), your application can crash.</li>
<li>Most of the heap-related problems are notoriously difficult to test. For example, a brief bout of testing often fails to uncover a storage leak that kills a program after a few hours, or weeks, of operation. Similarly, exceeding a real-time deadline because of nondeterminism can show up only when the heap reaches a certain fragmentation pattern. These types of problems are extremely difficult to reproduce.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2010/01/heap-of-problems/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A nail for a fuse</title>
		<link>http://embeddedgurus.com/state-space/2009/11/a-nail-for-a-fuse/</link>
		<comments>http://embeddedgurus.com/state-space/2009/11/a-nail-for-a-fuse/#comments</comments>
		<pubDate>Fri, 27 Nov 2009 17:13:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2009/11/27/a-nail-for-a-fuse/</guid>
		<description><![CDATA[If I were to search my soul, I&#8217;d have to admit that the use of assertions has helped me more than any other single technique, even more than my favorite state machines. But, the use of assertions, simple as they are, is surrounded by so many misconceptions and misunderstandings that it&#8217;s difficult to know where [...]]]></description>
			<content:encoded><![CDATA[<p>If I were to search my soul, I&#8217;d have to admit that the use of assertions has helped me more than any other single technique, even more than my favorite state machines. But, the use of assertions, simple as they are, is surrounded by so many misconceptions and misunderstandings that it&#8217;s difficult to know where to start. The discussion around the recent Jack Genssle&#8217;s article &#8220;<a href="http://www.embedded.com/columns/breakpoint/221800158">The Use of Assertions</a>&#8221; shows many of the misunderstandings.</p>
<p>I suppose that the main difficulties in understanding assertions lay in the fact that while the implementation of assertions is trivial, the effective use of assertions requires a paradigm shift in the view of software construction and the nature of software errors in particular.</p>
<p>Perhaps the most important point to understand about assertions is that they neither handle nor prevent errors, in the same way as fuses in electrical circuits don&#8217;t prevent accidents or abuse. In fact, a fuse is an intentionally introduced <span style="font-weight:bold">weak</span> spot in the circuit that is designed to fail sooner than anything else, so actually the whole circuit with a fuse is less robust than without it.</p>
<p>I believe that the analogy between assertions and fuses (which, by the way has been originally proposed by Niall Murphy in a private conversation at one of the Embedded Systems Conferences) is accurate and valuable, because it helps in making the paradigm shift in understanding many aspects of using assertions. Here I&#8217;d only like to elaborate just two aspects.    </p>
<p>First, the analogy to fuses correctly suggests that assertions work best in the &#8220;weakest&#8221; spots. Such &#8220;weak spots&#8221; are often found at the interface between components (e.g., preconditions in a function) but there are many others. The best assertions are those that protect the most of the system. In other words, the best assertions catch errors that would have the most impact on the rest of the system. </p>
<p>The second important implication of the fuse analogy is the issue of disabling assertions in the production code. As the comments to the aforementioned <a href="http://www.embedded.com/columns/breakpoint/221800158">article</a> suggest, most engineers tend to disable assertions before shipping the code, especially in the safety critical products. I believe that this is exactly <span style="font-weight:bold">backwards</span>.</p>
<p>I understand that the standard &#8220;assert.h&#8221; header file is designed to use assertions only in a debug build, so the macro assert() compiles to nothing when the symbol NDEBUG is defined. I strongly suggest rethinking this philosophy, because disabling assertions in the release configuration is like using nails, paper clips, or coins for fuses. Just imagine finding a nail in place of a fuse in a hospital&#8217;s operating room or in a dashboard of an airliner? What would you think of this sort of &#8220;repairs&#8221;? </p>
<p>Yet, by disabling assertions in our code we do exactly this.  </p>
<p>I believe it is very important to understand that assertions have a very important role to play, especially in the filed and especially in the mission-critical systems, because they add additional <span style="font-weight:bold">safety</span> layer in the software. Perhaps the biggest fallacy of our profession is the naïve optimism that our software will not fail. In a nutshell we somehow believe that when we stop checking for errors, they will stop occurring. After all&#8211;we don&#8217;t see them anymore. But this is not how computer systems work. An error, no matter how small, can cause catastrophic failure. With software, there are no &#8220;small&#8221; errors. Our software is either in complete control over the machine or it isn&#8217;t. Assertions help us know when we lose control. </p>
<p>So what do I suggest we do when the assertion fires in the filed? The proper course of action requires a lot of thinking and sometimes a lot of work. In safety-critical systems software failure should be part of the fault-tree analysis. Sometimes, reaching a fail-safe state requires some redundancy in the hardware. In any case, the assertion failures should be extensively tested.</p>
<p>But this is really the best we can do.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2009/11/a-nail-for-a-fuse/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Cute Creator</title>
		<link>http://embeddedgurus.com/state-space/2009/04/cute-creator/</link>
		<comments>http://embeddedgurus.com/state-space/2009/04/cute-creator/#comments</comments>
		<pubDate>Tue, 28 Apr 2009 17:26:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2009/04/28/cute-creator/</guid>
		<description><![CDATA[For a long time I&#8217;ve been looking for a good cross platform development environment that would allow fast exploration and navigation of C/C++ source code, not just editing of individual files. For a while I though that Eclipse will fit the bill, but as I wrote previously, the CDT (C/C++ Development Tooling) was really disappointing [...]]]></description>
			<content:encoded><![CDATA[<p>For a long time I&#8217;ve been looking for a good cross platform development environment that would allow fast exploration and navigation of C/C++ source code, not just editing of individual files. For a while I though that Eclipse will fit the bill, but as I wrote <a href="http://www.embeddedgurus.net/state-space/2007/09/emperors-new-clothes.html">previously</a>, the CDT (C/C++ Development Tooling) was really disappointing for me.</p>
<p>In this post I&#8217;d like to tell you about my recent big hope for a truly productive IDE, which is the <a href="http://www.qtsoftware.com/products">Qt Creator</a> from <a>qtsoftware.com</a>. Qt Creator is based on the popular cross-platform Qt framework and runs natively on Windows, Linux, BSD, Mac OS X, and some embedded platforms. No Java (as in the case of Eclipse) means speed and snappy interface. Qt Software (previously Trolltech, acquired in 2008 by Nokia) offers free downloads of Qt Creator for all major platforms.</p>
<p>Qt Creator is primarily targeted as the IDE for Qt-related development. However, the recently released version 1.1 (April 23, 2009) supports external projects, so adding your embedded or any other projects unrelated to Qt is easy.</p>
<p>For example, I&#8217;ve created an embedded project for a &#8220;game&#8221; shown in the screen shot below (click on the image to see it full-size):</p>
<div id="attachment_33" class="wp-caption alignnone" style="width: 310px"><a href="http://embeddedgurus.com/state-space/files/2009/04/QtCreator.jpg"><img class="size-medium wp-image-33" title="QtCreator" src="http://embeddedgurus.com/state-space/files/2009/04/QtCreator-300x185.jpg" alt="QtCreator" width="300" height="185" /></a><p class="wp-caption-text">QtCreator</p></div>
<p>The editing surface maximizes the screen real-estate for file viewing and supports sophisticated splitting, so that my favorite side-by-side code editing is easy.</p>
<p>As shown in the left pane, you can add to your project as many files in different directories as you like. Given this information, Qt Creator builds an internal database of all symbols in your code to allow you exploring and navigating through your source code quickly. For example, you can jump from symbol usage to its definition by pressing F2 (press Alt-back-arrow to jump back to the previous context).</p>
<p>Everything in the editor is designed to enhance quick navigation. For example, every editor pane has a drop-down list of functions and other elements in the file. The editor also supports selective viewing with collapsible/expandable code sections, so you can fit more information on the screen. To quickly view the collapsed section you can simply hover your mouse cursor over it.</p>
<p>I immensely like the support for project-wide searching (as well as search-and-replace), which is available at the bottom of the screen. This feature alone is worth installing the tool.</p>
<p>Even though it is so new, Qt Creator is already very interesting, free, cross-platform IDE with features comparable to Visual Studio 2008 and other best-in-class tools. Qt Software seems very committed to enhancing Qt Creator and I hope that Qt Creator will soon catch up with Eclipse as third-party plug-ins will be developed. One feature that I will be looking forward to is side-by-side code differencing. But already, it is a powerful, free, cross-platform tool that you should try.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2009/04/cute-creator/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Insects of the computer world</title>
		<link>http://embeddedgurus.com/state-space/2009/03/insects-of-the-computer-world/</link>
		<comments>http://embeddedgurus.com/state-space/2009/03/insects-of-the-computer-world/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 21:15:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Efficient C/C++]]></category>
		<category><![CDATA[MCUs]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2009/03/09/insects-of-the-computer-world/</guid>
		<description><![CDATA[The recent Jack Ganssle&#8217;s &#8220;Breakpoints&#8221; blog on Embedded.com makes an excellent point that the same forces (the Moore&#8217;s law), which drive down the prices of high-end processors open even more market opportunities at the low-end of the price spectrum. I also agree that the most deciding factor for the price of a single-chip microcontroller (MCU) [...]]]></description>
			<content:encoded><![CDATA[<p>The recent Jack Ganssle&#8217;s <a href="http://www.embedded.com/columns/breakpoint/215801305">&#8220;Breakpoints&#8221; blog</a> on <a href="http://www.embedded.com">Embedded.com</a> makes an excellent point that the same forces (the Moore&#8217;s law), which drive down the prices of high-end processors open even more market opportunities at the low-end of the price spectrum. I also agree that the most deciding factor for the price of a single-chip microcontroller (MCU) is the efficiency of its memory use, in other words, the code density. This becomes obvious when one looks at the silicon die of any MCU, which is completely dominated by the ROM and RAM blocks, the CPU being almost insignificant somewhere in the corner.</p>
<p>But, I would disagree with Jack&#8217;s statement that &#8220;tiny (8-bit) processors make more efficient use of memory&#8221;. From my experience with several single-chip MCUs I draw a different conclusion: the CPU size (8-, 16-, 32-bits) almost doesn&#8217;t matter for the code density. The deciding factor is how old a design is, whereas the newer instruction set architectures (ISAs) generally far outperform the older ISAs.</p>
<p>To support the point, I present below a table that shows the code size of a tiny state machine framework written in C (called QP-nano), which has been compiled for a dozen or so very different single-chip MCUs. The code consists of a small hierarchical state machine processor (called QEP-nano), and a tiny framework (called QF-nano). The QEP-nano consists mostly of a conditional logic to execute hierarchical state machines. QF-nano contains an event queue, a timer module, and a simple event loop. I believe that this code is quite representative to typical projects that run on these small MCUs.<br />
<code><br />
CPU type          C Compiler                    QEP-nano    QF-nano</code></p>
<p><code> (bytes)    (bytes)<br />
---------------+-------------------+----------+---------<br />
PIC18                MPLAB-C18                          3,214     2,072</code></p>
<p><code> (student edition)</code></p>
<p><code> ---------------+-------------------+----------+---------<br />
8051 (SiLabs)             IAR EW8051                    952             603</code></p>
<p><code>---------------+-------------------+----------+---------</code></p>
<p><code>PSoC (M8C)               ImageCraft M8C            2,765     2,425</code></p>
<p><code>---------------+-------------------+----------+---------</code></p>
<p><code>68HC08                   CodeWarrior HC(S)08           957      660</code></p>
<p><code>---------------+-------------------+----------+---------</code></p>
<p><code>AVR (ATmega)             IAR EWAVR                        541      650</code></p>
<p><code>---------------+-------------------+----------+---------</code></p>
<p><code>AVR (ATmega)            WinAVR(GNU)                     998      810</code></p>
<p><code>---------------+-------------------+----------+---------</code></p>
<p><code>MSP430                         IAR EW430                552            460</code></p>
<p><code>---------------+-------------------+----------+---------</code></p>
<p><code>M16C                             HEW4/NC30                         984            969</code></p>
<p><code>---------------+-------------------+----------+---------</code></p>
<p><code>TMS320C28x                 C2000                       369 words  331 words (Piccolo)                                                     738 bytes  662 bytes</code></p>
<p><code>---------------+-------------------+----------+---------</code></p>
<p><code>ARM7(ARM/THUMB)        IAR EWARM              588(THUMB)  1,112(ARM)</code></p>
<p><code>---------------+-------------------+----------+---------</code></p>
<p><code>ARM Cortex-M3    IAR EWARM                  524               504 </code></p>
<p><code>(THUMB2)</code></p>
<p><code> ---------------+-------------------+----------+---------<br />
</code><br />
Interestingly, the winner is MSP430, which is a 16-bit architecture.<br />
It seems that the 16-bit ISA hits somehow the &#8220;sweet spot&#8221; for the best code density, perhaps because the addresses are also 16-bit wide and are handled in a single instruction. In contrast, 8-bitters need multiple instructions to handle 16-bit addresses.</p>
<p>I would also point out the excellent code density (and C-friendliness) of the new ARM Cortex-M3, which is a modern 32-bit ISA, and still far outperforms all 8-bitters, including the good ol&#8217;8051.</p>
<p>On the other hand, the venerable PIC architecture is by far the worst (or, C un-friendly). That&#8217;s interesting, because this is the 8-bit market leader. I honestly don&#8217;t understand how Microchip makes money when their chips require the most silicon for given functionality. Clearly some other forces than just technical merits must be at work here.</p>
<p>In conclusion, I understand that my data is highly subjective and different code sets (and different compilers) could perhaps produce different results. However, I believe that the general trend is true and this is an <strong>important lesson</strong> for engineers selecting MCUs.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2009/03/insects-of-the-computer-world/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>RTOS Alternatives</title>
		<link>http://embeddedgurus.com/state-space/2009/01/rtos-alternatives/</link>
		<comments>http://embeddedgurus.com/state-space/2009/01/rtos-alternatives/#comments</comments>
		<pubDate>Wed, 07 Jan 2009 23:15:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[RTOS Multithreading]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2009/01/07/rtos-alternatives/</guid>
		<description><![CDATA[As hundreds of commercial and other RTOS offerings can attest, the greatest demand for third-party software in the embedded systems community is for the RTOS. But this is perhaps because most embedded developers believe that traditional preemptive RTOS on one end of the complexity spectrum and the customary superloop (main+ISRs) on the other are the [...]]]></description>
			<content:encoded><![CDATA[<p>As hundreds of commercial and other RTOS offerings can attest, the greatest demand for third-party software in the embedded systems community is for the RTOS. But this is perhaps because most embedded developers believe that traditional preemptive RTOS on one end of the complexity spectrum and the customary superloop (main+ISRs) on the other are the only choices for the embedded software architecture.</p>
<p>However, a little less know alternative is *event-driven* software structure based on an event-driven framework and encapsulated state machines (called active objects in the UML). This active object-based architecture is not new, and in fact, has been in quite widespread use for at least two decades. Virtually all commercially successful design automation tools on the market today (Telelogic Rhapsody, Rose Real-Time, IAR visualSTATE, Mathworks StateFlow, and many others) are based on hierarchical state machines and incorporate internally a variant of an event-driven framework. For example, Rhapsody generates code either for the Object eXecution Framework (OXF) or the Interrupt-Driven Framework (IDF). OXF requires a traditional RTOS for preemptive scheduling, while IDF was created specifically to avoid the need for an RTOS.</p>
<p>Most developers are accustomed to the basic sequential control, in which a program (a task in an RTOS) waits for events in various places in its execution path by either actively polling for events or passively blocking on a semaphore or other such RTOS mechanism. Though this approach is functional in many situations, it doesn&#8217;t work very well when the system must timely react to multiple events whose arrival times and order one cannot predict. The fundamental problem is that while a sequential task is waiting on one kind of event, it is not doing any other work and is not *responsive* to other events.</p>
<p>Event-driven programming requires a distinctly different way of thinking than conventional sequential programs, such as &#8220;superloops&#8221; or tasks in a traditional RTOS. Event-driven systems are structured according to the Hollywood principle, which means &#8220;Don’t call us, we’ll call you&#8221;. So, an event-driven program is not in control while waiting for an event; in fact, it’s not even active. Only once the event arrives, the program is called to process the event and then it quickly relinquishes the control again. This arrangement allows an event-driven system to wait for many events in parallel, so the system remains *responsive* to all events it needs to handle.</p>
<p>This scheme has three important consequences. First, it implies that an event-driven system is naturally divided into the application, which actually handles the events, and the supervisory event-driven infrastructure (framework), which waits for events and dispatches them to the application. Second, the control resides in the event-driven infrastructure, so from the application standpoint, the control is inverted compared to a traditional sequential program. And third, the event-driven application must return control after handling each event, so the execution context cannot be preserved in the stack-based variables and the program counter as it is in a sequential task. Instead, the event-driven application becomes a *state machine*, or actually a set of collaborating state machines that preserve the context from one event to the next in the static variables.</p>
<p>Traditionally, event-driven programming was done with a specific design-automation tool, such as Rose-RT or Rhapsody (now both acquired by IBM). But recently, lightweight, open source event-driven frameworks became available. The lightweight frameworks allow direct coding of hierarchical state machines (UML statecharts) in C or C++ and then combining multiple concurrent state machines into systems, all without big tools (e.g., see <a href="http://www.state-machine.com/">www.state-machine.com</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2009/01/rtos-alternatives/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Make the most of side-by-side code differencing</title>
		<link>http://embeddedgurus.com/state-space/2008/06/make-the-most-of-side-by-side-code-differencing/</link>
		<comments>http://embeddedgurus.com/state-space/2008/06/make-the-most-of-side-by-side-code-differencing/#comments</comments>
		<pubDate>Wed, 11 Jun 2008 15:36:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2008/06/11/make-the-most-of-side-by-side-code-differencing/</guid>
		<description><![CDATA[I&#8217;m constantly amazed how many developers shoot themselves in the foot by defeating the benefits of side-by-side source code differencing, which is perhaps the most routinely used technique in daily code development and maintenance with any VCS (Version Control System). In this post, I&#8217;d like to share a few tips for making the most of [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m constantly amazed how many developers shoot themselves in the foot by defeating the benefits of side-by-side source code differencing, which is perhaps the most routinely used technique in daily code development and maintenance with any VCS (Version Control System). In this post, I&#8217;d like to share a few tips for making the most of side-by-side differencing, which in my view should be adopted into every coding standard.</p>
<p>First of all, to benefit from side-by-side diff you need to limit the width of your lines so that you don&#8217;t need to scroll horizontally to see all the code. Countless bugs slip into a VCS, because they are hidden off screen during the final merge and people are simply tired of constantly scrolling back and forth. (All GUI usability studies agree that horizontal scrolling of text is always a bad idea.)</p>
<p>Granted, the modern high-resolution wide screens offer a lot of horizontal pixels, but ultimately you&#8217;ll always run out of the screen real estate if you allow lines to go on for miles. The column width must obviously allow comfortable viewing two code listings side-by-side, but you should also budget some horizontal space for the directory-tree view, vertical sliders, line numbers, and line margins, as shown in the screen shot below. I&#8217;ve been using the column width limit of no more than 78 characters. Your limit could perhaps be higher, but you <strong>must</strong> set such a limit and then enforce it without exceptions.</p>
<p><img src="http://www.state-machine.com/resources/side_by_side_diff.jpg" alt="side-by-side diff" vspace="10" /></p>
<p>I can see two main reasons why people write very long lines. The first is long strings in the code. But C or C++ allow writing wide string constants in the following way:</p>
<p><code>char const s1[] =    "This long string is acc\</code></p>
<p><code>eptable to all C compilers.";</code></p>
<p><code>char const s2[] =    "This long string is permissible "</code></p>
<p><code> "in ANSI C.";</code></p>
<p>In other words, you can either use a backslash &#8216;\&#8217; to terminate a string and continue in the next line, or you can terminate a string normally with a double quote &#8216;&#8221;&#8216;, and an ANSI C compiler will concatenate such adjacent strings into a single zero-terminated string.</p>
<p>The second reason for long lines are preprocessor macros. Here again, you can use the backslash &#8216;\&#8217; to break up a longer macro into lines. For example:<br />
<code>#define err(flag, msg) if (flag) \   printf(msg)</code></p>
<p>is the same as</p>
<p><code>#define err(flag, msg) if (flag) printf(msg)</code></p>
<p>The use of a backslash for breaking up longer lines brings up the issue of the end-of-line convention and the use of white space in your source code in general.</p>
<p>Let me start with the end-of-line convention. The issue here is that the backslash continuation won&#8217;t work unless the &#8216;\&#8217; character is <strong>immediately</strong> followed by the end-of-line. Unfortunately, at lest two incompatible end-of-line conventions are in widespread use. The DOS/Windows end-of-line convention consists of the pair of characters CR-LF (0&#215;0D, 0&#215;0A in hex) to terminate lines. In contrast the UNIX™ end-of-line convention uses only one LF character (0&#215;0A). As it turns out, Unix-like machines (e.g. Linux) are confused by the DOS end-of-line convention and will <strong>not</strong> correctly recognize the backslash-continuation, which looks like &#8216;\&#8217;-CR-LF (0&#215;5C, 0&#215;0D, 0&#215;0A), instead of &#8216;\&#8217;-LF (0&#215;5C, 0&#215;0A).</p>
<p>My recommendation is to use consistently only the UNIX end-of-line convention, even on Windows machines. In my experience all Windows-based compilers have no problems with the UNIX convention, including the ancient tools from the DOS-era. As I mentioned, the converse is not true.</p>
<p>And finally, let me talk about the use of white space (spaces, tabs, end-of-line) in general. Obviously, to benefit from source code differencing you&#8217;d like to see only the relevant differences and differences in white space only are typically not relevant. Many code-differencing tools offer an option to ignore white space, but I would not recommend relying on it. Are files with different sizes really identical? And also, as I said before, extra spaces or tabs after the backslash, but before the end-of-line, are not allowed.</p>
<p>As far as tabs are concerned, I&#8217;d strongly recommend <strong>not</strong> to use them at all. Tabs are rendered differently by different editors and printers and bring only insignificant memory savings. Preferably, you should disable tabs at the editor level. At the very least, you should replace all tabs by spaces (&#8220;untabify&#8221;) before saving the file. As for spaces, I recommend removing any trailing spaces that precede the end-of-line character (LF).</p>
<p>Obviously, you can and should automate the source code cleanup. I use the QCLEAN utility (available <a href="http://www.state-machine.com/resources/qclean.zip">here</a> under the GPL license) for cleaning up the code from tabs, trailing blanks, and to enforce the Unix end-of-line convention. The simple console QCLEAN Windows executable scanns recursively all source files (.C, .CPP, .H, .ASM, .S, Makefile, etc.) down from the directory in which it is invoked. The following two listings show a code snippet before and after cleanup with the QCLEAN utility (spaces are shown as dots, tabs as \t, DOS end-of-lines as \r\n, UNIX end-of-lines as \n).</p>
<p>before cleanup:<br />
<code>.\t...\r\n</code></p>
<p><code>class.Foo.:.public.Bar.{...\n</code></p>
<p><code>public:.\r\n</code></p>
<p><code>\tFoo(int8_t.x,.int16_t.y,.int32_t z).//..ctor..\n</code></p>
<p><code>....:.Bar(x,.y),.m_z(z)....\n</code></p>
<p><code>....{}.............\n</code></p>
<p><code>.\t..\n</code></p>
<p><code>....virtual.~Foo();\t... //.xtor........\r\n</code></p>
<p><code>....virtual int32_t doSomething(int8_t.x);.//.method..\r\n </code></p>
<p>after cleanup with QCLEAN:<br />
<code>\n</code></p>
<p><code>class.Foo.:.public.Bar.{\n</code></p>
<p><code>public:\n</code></p>
<p><code>....Foo(int8_t.x,.int16_t.y,.int32_t z).//..ctor\n</code></p>
<p><code>....:.Bar(x,.y),.m_z(z)\n</code></p>
<p><code>....{}\n</code></p>
<p><code>\n</code></p>
<p><code>....virtual.~Foo();... //.xtor\n</code></p>
<p><code>....virtual int32_t doSomething(int8_t.x);.//.method\n<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2008/06/make-the-most-of-side-by-side-code-differencing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Object-based programming in C</title>
		<link>http://embeddedgurus.com/state-space/2008/01/object-based-programming-in-c/</link>
		<comments>http://embeddedgurus.com/state-space/2008/01/object-based-programming-in-c/#comments</comments>
		<pubDate>Mon, 21 Jan 2008 00:11:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://embeddedgurus.com/state-space/2008/01/21/object-based-programming-in-c/</guid>
		<description><![CDATA[Embedded developers abandon C++ in droves. According to the 2007 survey published in the ESD magazine, the C++ use declined by one-third compared to year before, which was offset by an equal rise in popularity of C—the only viable alternative in embedded.
Even though the last year was most dramatic, the trend has been actually continuing [...]]]></description>
			<content:encoded><![CDATA[<p>Embedded developers abandon C++ in droves. According to the <a href="http://www.embedded.com/design/opensource/201803499">2007 survey</a> published in the ESD magazine, the C++ use declined by one-third compared to year before, which was offset by an equal rise in popularity of C—the only viable alternative in embedded.</p>
<p>Even though the last year was most dramatic, the trend has been actually continuing for a number of years. This couldn&#8217;t go unnoticed by UML tool vendors, who desparately have been trying to cater to C programmers. For example, you can check out the DDJ article &#8220;<a href="http://www.ddj.com/web-development/184401948">UML for C Programmers</a>&#8221; (which seems to be pretty exact re-print of the Embedded Systems Conference paper &#8220;<a href="https://www.cmpevents.com/ESCw08/a.asp?option=C&amp;V=11&amp;SessID=6716">UML for C-Based Embedded Systems</a>&#8220;). To my surprise, nether this article, nor the ESC class mention any well-known techniques of mapping objects and classes to C. I’m sure that it is not what UML vendors like. After all, UML is crippled without objects. (The only real meat remaining are state machines.) But I suppose that the marketing departments of I-Logix/Telelogic have done their homework. Apparently <strong>embedded developers</strong> don’t like to hear about objects anymore.</p>
<p>I find this really disturbing. It seems that &#8220;object&#8221; and (pardon my language) &#8220;class&#8221; are becoming dirty words in the embedded circles. C++ decline is one thing. But abandoning objects is a different story. Aren’t we throwing out the baby with the bath water?</p>
<p>One would assume that the 21st-century software developers have objects in their bones and everyone knows how to program with objects in any language, including C. Apparently increasing number of us don’t know that object technology is a <strong>way of design</strong>, not the use of any particular language or tool. Most design and implementation techniques now associated with C++, Smalltalk, or Java, actually long predate these languages.</p>
<p>So here is how you implement a Point class in C (a Point that you can put on a screen):<br />
<code>typedef struct PointTag {</code></p>
<p><code> int16_t x;   /* x-coordinate */</code></p>
<p><code> int16_t y;   /* y-coordinate */</code></p>
<p><code>} Point;</code></p>
<p><code>void Point_ctor(Point *me, int16_t x, int16_t y) {</code></p>
<p><code> me-&gt;x = x;</code></p>
<p><code> me-&gt;y = y;</code></p>
<p><code>}</code></p>
<p><code>void Point_move(Point *me, int16_t dx, int16_t dy) {</code></p>
<p><code> me-&gt;x += dx;</code></p>
<p><code> me-&gt;y += dy;</code></p>
<p><code>}</code></p>
<p><code>int16_t Point_dist(Point const *me, Point const *other) {</code></p>
<p><code> int16_t dx = me-&gt;x – other-&gt;x;</code></p>
<p><code> int16_t dy = me-&gt;y – other-&gt;y;</code></p>
<p><code> return (int16_t)sqrt(dx*dx + dy*dy);</code></p>
<p><code>}. . .</code></p>
<p><code>/* example of using Point objects */</code></p>
<p><code>Point foo, bar, tar;  /* multiple instances of Point */</code></p>
<p><code>int16_t dist;</code></p>
<p><code>Point_ctor(&amp;foo, 0, 0);Point_ctor(&amp;bar, 1, 1);</code></p>
<p><code>Point_ctor(&amp;tar, -1, 2);</code></p>
<p><code>dist = Point_dist(&amp;foo, &amp;bar);</code></p>
<p><code>Point_move(&amp;tar, 2, 4);dist = Point_dist(&amp;bar, &amp;tar);. . .</code></p>
<p>You can create any number of Point objects as instances of the Point struct. You need to initialize each point with the &#8220;constructor&#8221; Point_ctor(). You manipulate the Points only through the provided functions, which take the pointer &#8220;me&#8221; as the first argument. The &#8220;me&#8221; pointer corresponds directly to the implicit &#8220;this&#8221; pointer in C++.</p>
<p>Moreover, you can as easily implement single inheritance. Assume for example, that you need to add a color attribute to Points. Instead of developing such a colored-Point from scratch, you can <strong>inherit</strong> most what’s common from Point and add only what’s different. Here’s how you do it:<br />
<code>typedef struct ColoredPointTag {</code></p>
<p><code> Point super;    /* derives from Point */</code></p>
<p><code> uint16_t color; /* 16-bit color */</code></p>
<p><code>} ColoredPoint;</code></p>
<p><code>void ColoredPoint_ctor(ColoredPoint *me, </code></p>
<p><code> int16_t x, int16_t y, uint16_t color) {</code></p>
<p><code> Point_ctor(&amp;me-&gt;super, x, y); /* call superclass’ ctor */</code></p>
<p><code> me-&gt;color = color;</code></p>
<p><code>}<br />
...</code></p>
<p><code>/* example of using ColoredPoint objects */</code></p>
<p><code>ColoredPoint p1, p2;int16_t dist;<br />
ColoredPoint_ctor(&amp;p1, 0, 2, RED);</code></p>
<p><code>ColoredPoint_ctor(&amp;p2, 0, 2, BLUE);<br />
/* re-use inherited function */</code></p>
<p><code>dist = Point_dist((Point *)&amp;p1, (Point *)&amp;p2);</code></p>
<p>As you can see, you implement inheritance by literally embedding the superclass (Point) as the first member of the subclass (ColoredPoint). Such nesting of structures always aligns the first data member &#8217;super&#8217; at the beginning of every instance of the derived structure. This alignment is guaranteed by the C standard. Specifically, WG14/N1124 Section 6.7.2.1.13 says: &#8220;&#8230; A pointer to a structure object, suitably converted, points to its initial member. There may be unnamed padding within a structure object, but not at its beginning&#8221;. This alignment lets you treat a pointer to the derived ColoredPoint struct as a pointer to the Point base struct. All this is legal, portable, and blessed by the Standard.</p>
<p>With this arrangement, you can always safely pass a pointer to ColoredPoint to any C function that expects a pointer to Point. Consequently, all functions designed for the Point structure are automatically available to the ColoredPoint structure. They are all <strong>inherited</strong>.</p>
<p>There is really nothing to it.</p>
]]></content:encoded>
			<wfw:commentRss>http://embeddedgurus.com/state-space/2008/01/object-based-programming-in-c/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
