Thursday, April 22, 2010

Efficient C Coding Guidelines for Embedded Systems

The C language is like a carving knife: simple, sharp, and extremely useful in skilled hands. Like any sharp tool, C can injure people who don’t know how to handle it.
Andrew Koenig


Here are some ways to avoid the injuries. In my next blog on this topic I shall try to post some of the coding guidelines that I follow in detail. The methods mentioned here again are indicative only. Also the methods may or may not be suitable for your embedded application. The methods are general guidelines.

·         Follow Coding Standards
o   Helps in readability and maintenance

·         Set the compiler to highest level of warnings
o   Never allow a warning to get into production code
o   Warning is a ticking time-bomb

·         All switches to have default case

·         Question all the global variables and their needs

·         Make all variables that can be CONST’s to be CONST’s

·         Variables SHOULD be initialized before use

·         Static Analysis
o   Static analysis are always better than testing

·         Avoid Memory Corruption
o   OS, Libraries and application all run in one address space leading to high possibility of memory corruption
o   Avoid memory corruption by
§  initializing pointers before use,
§  taking care of memory boundaries before incrementing/decrementing pointers
§  allocating appropriate stack size while keeping worst case scenario of interrupt and call nesting in mind

·         Avoid blocking calls inside ISR

2 comments: