Embedded C/C++

Moderators: Lundin
Number of threads: 209
Number of posts: 392

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Static variable initialization in Embedded C Posted by yukixxyu on 15 Apr 2008 at 7:35 PM
I'm kind of confused about the static variable initialization in embedded C. In ANSI C they are not auto-initialized, meaning, you need to initialize them manually, although some compilers do this for you. How about embedded C? Is it universally agreed that all embedded C compilers will do the auto-initialization, or still case-by-case?
Report
Re: Static variable initialization in Embedded C Posted by Lundin on 15 Apr 2008 at 11:39 PM
First of all in ISO C (ANSI C), all static and global variables must be initialized before the program starts. If the programmer didn't do this explicitly, then the compiler must set them to zero. If the compiler doesn't do this, it doesn't follow ISO C. Exactly how the variables are initialized is however unspecified by the standard.

So if the embedded compiler claims to be ISO C compatible, it must initialize statics (and globals) at startup. Since many embedded systems are ROM-based rather than RAM-based, it means that the compiler has to put code in the beginning of the program copying values from the ROM to the RAM.

There are two problems appearing because of this:

- You get a load of code in the beginning of your program, causing program startup to be slower.

- In safety-critical realtime systems (or in any bug-free system), it is poor practice to rely on variables in RAM. From the point of initialization to the first time that variable is used, weeks or years might have passed. This isn't a programming problem, it is a hardware problem: RAM memory tends to be volatile and untrustworthy.

The only solution to these problems is to write the code so that all initialization of statics/globals is done in runtime, just before the variable is used. Once this is done, you can usually disable the "copy-down" functionality of the compiler. That way you can remain ISO C compatible while your program gets faster and safer.
Report
Re: Static variable initialization in Embedded C Posted by yukixxyu on 23 Apr 2008 at 7:10 PM
Thank you for your explanation.



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.