What is the difference between static
global and non-static
global identifier in C++?

- 12,111
- 21
- 91
- 136

- 1,829
- 1
- 19
- 41
-
2"Static global" -- what do you mean by that? – Andrzej Oct 31 '12 at 16:05
-
2@Andrzej a global with the `static` keyword prefixing the type. `static int x = 5;` at global scope for example. – Seth Carnegie Oct 31 '12 at 16:24
4 Answers
Static limits the scope of the variable to the same translation unit.
A static global variable has internal linkage.
A non-static global variable has external linkage.
-
If a non-static global has external linkage, what's the use of `extern`? – rubenvb Oct 31 '12 at 16:07
-
@rubenvb: The answer to your Q is explained in detail in the link inline to answer. – Alok Save Oct 31 '12 at 16:09
-
2@rubenvb `extern` means that it's a declaration and not a definition, like the prototype for a function. – Seth Carnegie Oct 31 '12 at 16:24
-
@SethCarnegie: this is true only if there's no initializer nor function body and so on (§3.1/2). @rubenvb: In an anonymous namespace, names have internal linkage per default, but you can make them explicitly `extern` again. – dyp Oct 31 '12 at 22:13
-
@Downvoter: If there is any technical reasoning for the downvote please enlighten us all with that reason. – Alok Save Nov 01 '12 at 03:10
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.

- 400,186
- 35
- 402
- 621
-
3More specifically: using `static` prevents the linker from exporting the symbol from that translation unit. – cdhowie Oct 31 '12 at 16:06
Global Non static variables are accessable from other files whereas static global variables are not

- 168,305
- 31
- 280
- 331
-
1Of course, they are "accessible" via pointers. They just "cannot be referred to by names from scopes of other translation units" (§3.5). – dyp Oct 31 '12 at 22:05
-
1@DyP I think it's obvious that Rahul meant that variable isn't accessible by it's name. – Pavel P Oct 31 '12 at 22:34
If you don't know what the difference is, correct answer will probably be even more confusing to you. In short, static
s of a class aren't realted to statics at file scope. Statics of a class are esentially identical to regular variables, but they will have to be referenced by prefixing them with class name. Statics at file scope are regular variables that are local to the file only. To understand what that means, try to add two variables with the same name into a single project. You will get linker errors because there are multiple identical symbols. By making symbols static you will avoid that problems and variable's name won't be accessible from outside the file.

- 39
- 2