Gopi
Gopi

Reputation: 19864

What is the difference between static and non static global

static uint32_t a[20] = {0};

and

uint32_t a[20] = {0};

I use both of them in the code

a[0] = 1;

and so on....

When I make the variable static and use it I get an error

variable "a" was declared but never referenced

but when I remove static things work fine.

In both the cases the array a is a global one.

The error is with the MACROS .

Array declaration is done and it is used by some platform and I don't see an error on that. Same code provides an error because this declaration/array is not used on other platform.

My bad !!!!

static uint32_t a[20] = {0};
void func()
{
 ...............
   #ifdef ABC

   a[0] = 1;

   #endif
 ................
}

Now compile on platform ABC no error compile on some non ABC platform there is an error.

Solution: Wrap global also under the respective macro

#ifdef ABC
static uint32_t a[20] = {0};
#endif

Upvotes: 3

Views: 837

Answers (2)

sjsam
sjsam

Reputation: 21965

The keyword static

Case 1 : When used in file scope

Example :

static int x=0; // declared outside main() and all functions

means the the variable can be used only within the translation unit, ie the file which contains it.

So you cannot do

extern int x; // from another file

Case 2 : When used in block scope

Example

somefunction()
{
static int x=0;
x++; // x acting as a counter here
}

The variable x stays put(or it is not reinitialized) during different invocations of the function. You can use it as a function variable, for example, as a counter to find how many times a function is called. The scope is limited to the function block.


Regarding the warning :

variable "a" was declared but never referenced

The memory allocated for an automatic variable is freed when it goes out of context. But this is not the case with static variables. They stay put till the end of the execution. If you don't use a static variable, the compiler may warn you regarding this - I guess - so that you could avoid such a declaration.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

The major difference is, when defined as static, the scope of the array is limited to the translation unit, while , without static, the scope in not limited to the translation unit.

Quoting C11, chapter §6.2.2

If the declaration of a file scope identifier for an object or a function contains the storage class specifier static, the identifier has internal linkage.

So, in case of a static global, you cannot use that variable outside of the translation unit.

Upvotes: 5

Related Questions