Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a global or static declaration safer in an embedded environment?

Tags:

c

embedded

I have a choice to between declaring a variable static or global.

I want to use the variable in one function to maintain counter.

for example

void count()
{
   static int a=0;
   for(i=0;i<7;i++)
   {
      a++;
   }

}

My other choice is to declare the variable a as global. I will only use it in this function count().

Which way is the safest solution?

like image 940
sam_k Avatar asked Dec 06 '22 18:12

sam_k


2 Answers

It matters only at compile and link-time. A static local variable should be stored and initialised in exactly the same way as a global one.

Declaring a local static variable only affects its visibility at the language level, making it visible only in the enclosing function, though with a global lifetime.

A global variable (or any object in general) not marked static has external linkage and the linker will consider the symbol when merging each of the object files.

A global variable marked static only has internal linkage within the current translation unit, and the linker will not see such a symbol when merging the individual translation units.

like image 196
Blagovest Buyukliev Avatar answered Mar 01 '23 23:03

Blagovest Buyukliev


The internal static is probably better from a code-readability point of view, if you'll only ever use it inside that function.

If it was global, some other function could potentially modify it, which could be dangerous.

like image 35
Nick Shaw Avatar answered Mar 02 '23 00:03

Nick Shaw