Thought Leadership

Data types and code portability

I recently attended a presentation about the challenges with porting code from 8/16-bit CPUs to 32-bit devices. The speaker addressed all the major issues, giving me a few things to think about. One area that particularly caught my attention was the thorny issue of C language data types. With the intention of making it easy to write portable code, the specification for (traditional ANSI) C explicitly avoids specifying the bit size of data types. The effect upon some embedded code is quite the reverse, as data size may be a concern …

In the presentation, the speaker pointed out that a compiler for an 8-bit CPU would probably size int to be 16 bits. So code would need to be modified to make any int variable a short instead. I think that this is very short-sighted [no pun intended!]. A better approach is to replace all the standard data types with typedefs that indicate size – U8, U16, U32, S8, S16 … – and store these in a header file. Then modify the code to suit. Porting the code to another compiler just needs that header file to be edited appropriately.

I was rather taken aback by an example used in this presentation. It showed a loop, which simply incremented a variable (on a timer tick). A particular function was called each time the value wrapped around to zero. So changing from 16 to 32 bits would result in it being called every 4 billion ticks instead of every 65 thousand. Although this is true, it is appalling programming style. Clearly the variable should be loaded with the number of ticks and counted down as that code would be no less efficient, but infinitely more readable.

Colin Walls

I have over thirty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles and two books on embedded software, I am a member of the marketing team of the Mentor Graphics Embedded Systems Division, and am based in the UK. Away from work, I have a wide range of interests including photography and trying to point my two daughters in the right direction in life. Learn more about Colin, including his go-to karaoke song and the best parts of being British: http://go.mentor.com/3_acv

More from this author

This article first appeared on the Siemens Digital Industries Software blog at https://blogs.sw.siemens.com/embedded-software/2011/07/11/data-types-and-code-portability/