what's the difference

what's the difference between the two global declarations: static int i; int i;
They are both definitions but the latter has external linkage, that is it can be used by the linker to resolve undefined symbols declared in other translation units, while the former has internal linkage and it can be used only in the translation unit where it is defined.

Suppose you have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//a.cpp

int i;

//b.cpp

static int i;

//main.cpp

extern int i;
int main( ) {
  std::cout << i << std::endl;
} 


Now if you do:
g++ main.cpp a.cpp // Fine it will produce the exectuble.
g++ main.cpp b.cpp // It will throw an undefined reference error.

The use of the keyword static for global variable with internal linkage is deprecated. You should use an unnamed namespace instead:

1
2
3
namespace {
int i;
}

and you generally do not want to declare variables (or functions) with global scope as they will pollute the global namespace with the possibility of name clashes.
thank u ^_^
Topic archived. No new replies allowed.