Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ global vs static global [duplicate]

Possible Duplicate:
Static vs global

I'm confused about the differences between global and static global variables. If static means that this variable is global only for the same file then why in two different files same name cause a name collisions?

Can someone explain this?

like image 997
Vladp Avatar asked Oct 20 '11 14:10

Vladp


People also ask

Is static the same as global?

The difference between a static variable and a global variable lies in their scope. A global variable can be accessed from anywhere inside the program while a static variable only has a block scope.

What is static global in C?

A global static variable is one that can only be accessed in the file where it is created. This variable is said to have file scope. Constant Variables. In C, the preprocessor directive #define was used to create a variable with a constant value.

What is difference between static global and non static global variable in C?

A global static variable is only available in the translation unit (i.e. source file) the variable is in. A non-static global variable can be referenced from other source files.

What is a static global?

A static variable can be either a global or local variable. Both are created by preceding the variable declaration with the keyword static. A local static variable is a variable that can maintain its value from one function call to another and it will exist until the program ends.


1 Answers

Global variables (not static) are there when you create the .o file available to the linker for use in other files. Therefore, if you have two files like this, you get name collision on a:

a.c:

#include <stdio.h>  int a;  int compute(void);  int main() {     a = 1;     printf("%d %d\n", a, compute());     return 0; } 

b.c:

int a;  int compute(void) {     a = 0;     return a; } 

because the linker doesn't know which of the global as to use.

However, when you define static globals, you are telling the compiler to keep the variable only for that file and don't let the linker know about it. So if you add static (in the definition of a) to the two sample codes I wrote, you won't get name collisions simply because the linker doesn't even know there is an a in either of the files:

a.c:

#include <stdio.h>  static int a;  int compute(void);  int main() {     a = 1;     printf("%d %d\n", a, compute());     return 0; } 

b.c:

static int a;  int compute(void) {     a = 0;     return a; } 

This means that each file works with its own a without knowing about the other ones.


As a side note, it's ok to have one of them static and the other not as long as they are in different files. If two declarations are in the same file (read translation unit), one static and one extern, see this answer.

like image 65
Shahbaz Avatar answered Sep 23 '22 09:09

Shahbaz