source = c++ primer Sam's publishing
- file-scope variables with external (1 - 3) and internal (4) linkage
- file 1
int errors = 20;
file 2
void foo() {
cout << errors; // error
- file 1
int errors = 20; external declaration
file 2
int errors; //invalid declaration
void foo() {
cout << errors; // error
- file 1
int errors = 20; external declaration
file 2
extern int errors; //refers to errors from file1
void foo() {
cout << errors;
"the keyword extern indicates a reference declaration, i.e. a declaration elsewhere.
- file 1
int errors = 20; external declaration
file 2
static int errors = 5; //known to file2 only; applying the static keyword gives it static linkage
void foo() {
cout << errors;
}
- static keyword inside a block gives a local variable with no linkage works for functions and variables alike
- const
"whereas a global variable has external linkage by default, a const global variable has internal linkage by default."
i.e. const = static
internal linkage means that const declarations in the header can be made in each file. The extern keyword not required. Therefore each file which includes the header has its own set of constants and doesn't share them.
so declare the header constants as constants. e.g. extern const int states = 50;. Of course, declare merely s const int states = 50; in each additional source file.
return to top