Friday, October 31, 2008

Embedded Coding Style

My recent tryst with some "C" code written in Assembly like fashion has forced me to write this article up. I have been programming embedded systems for quite some time now. For those who are not aware, most of the embedded processors ( for the automotive domain) come with substantial amount of RAM and ROM spaces. Hence, it makes sense to write some what architectured code ( if not 100% for efficiency and optimization reasons).
"C" coding can get pretty messy sometimes if we dont architecture the code appropriately because of the very nature of language. "C" is a procedure oriented language and hence doesnot provide very clean natural organization of data ( like in case of C++, where classes can be used to hold all the logical data and operations together). Hence, personally i have used structures in C to hold all my data-memebers in a single nutshell.
There are some good and bad parts about a Structure. The good part is that it encapuslates all the data i need into one shell. The bad part is padding. If you dont arrange the members in your struct carefully you will end up eating up more memory than you would really need. Typically arrange the smallest member on the top and progressively the bigger ones so that there are fewer padding holes created in your stucture variable.
The other hint that i got from both Nec and CC compilers is to use scopes sensibly. What that means? Simply, choose a scope for a variable based on needs. There is not much gained by making all your variables global. Hence, as far as possible try to limit the scope of your variables to whatever is the minium needed. Also try to ensure that scope you have chosen, explain the logical boundaries of the variable
Ex.
void My_StateMachine(void)
{
switch(state) /* make state global if there is something which is using the state outside of this function, else make it a static inside the function */
}

Why am i telling you all this? Well you already know the answer in the first line of this article. It is much simpler to maintain software where the scope of variables are limited logically. Too many Globals means that too many blocks of softwares can change the variables in your system. This can lead to hard to solve bugs in future.

No comments: