LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

To be or not to be static?

After all these years of programming in �C�, I still find myself asking when to declare a variable static. I had adopted the notion that if variables where to be local then I should declare them automatic (e.g. int myvariable;). However I was working on a new application that caused a stack overflow every time a particular function was called. This particular function had dozens of local variables. Changing all of the local variables to static fixed the stack overflow problem. I think that this has something to do with how the system deals with the data stack when one function calls another but I don�t have a clear understanding of how know when or when not to use static variables. Is there a �rule of thumb�?

Thanks
0 Kudos
Message 1 of 2
(3,001 Views)
Glen...

Whilst I cannot quickly answer your question, here is a link to a webpage that provides an explanation as to the use / definition of the Storage Classes (static / extern / etc etc).

As you say, locals are stored upon the stack when the function is called, so if you exceed the stack allocation witin your function it will cause problems, fixed only by extending the size of the stack, or as you did by making them static (i.e. global - note: not file scope global).
Globals (statics and externs use memory space that has been allocated 'off the stack' and hence do not create problems, other than the persistance of the data itself, and the possibilites of memory leaks etc etc...

Quotes:
The auto (which is basically what your locals are) storage class specifier lets
you define a variable with automatic storage; its use and storage is restricted to the current block. The storage class keyword auto is optional in a data declaration. It is not permitted in a parameter declaration. A variable having the auto storage class specifier must be declared within a block. It cannot be used for file scope declarations.

Because automatic variables require storage only while they are actually being used, defining variables with the auto storage class can decrease the amount of memory required to run a program. However, having many large automatic objects may cause you to run out of stack space



I have a series of other links and will post if I can find them...


http://www.tru64unix.compaq.com/faqs/publications/base_doc/DOCUMENTATION/V40F_HTML/AQTLTBTE/DOCU_023.HTM

http://eel.st.usm.edu/~seyfarth/css334/c-6-3-7.html

http://www.psu.edu/dept/cac/ait/nic_group/Soft_Lang/C/VAC/doc/concepts/cudecblk.htm
Message 2 of 2
(3,001 Views)