35

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

tshepang
  • 12,111
  • 21
  • 91
  • 136
Fahad Siddiqui
  • 1,829
  • 1
  • 19
  • 41

4 Answers4

37

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.

Good Read:
What is external linkage and internal linkage?

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 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
12

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 3
    More specifically: using `static` prevents the linker from exporting the symbol from that translation unit. – cdhowie Oct 31 '12 at 16:06
3

Global Non static variables are accessable from other files whereas static global variables are not

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 1
    Of 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
3

If you don't know what the difference is, correct answer will probably be even more confusing to you. In short, statics 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.

eric
  • 39
  • 2