Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Static variable initialization in Embedded C

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?


  • LundinLundin Posts: 3,711
    First of all in ISO C (ANSI C), all static and global variables [italic]must[/italic] 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 [italic]how[/italic] 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.
  • yukixxyuyukixxyu Posts: 6
    Thank you for your explanation.
Sign In or Register to comment.