Global variable and static global variable

Viewed 157

Is there any difference in C++ between global variable/const and global static variable/const? Declared in cpp file or a header file.

static const int x1 = someFunction(5);
const int x2 = someFunction(6);
static int x3 = someFunction(5);
int x4 = someFunction(6);

int main()
{
...
2 Answers

Case I: For const objects

Similarity

In both versions, the variables have internal linkage. That is, both x1 and x2 have internal linkage.

Difference

In case of static const int x1 the variable is explicitly static while in case of const int x2 the variable is implicitly static. But note that they both still have internal linkage.

Case II:For nonconst objects

Similarity

Both x3 and x4 are nonconst meaning we can modify them.

Difference

The variable x3 has internal linkage while the variable x4 has external linkage.

NOTE: This only applies when the variables aren't const. I've undeleted this answer at the OP's request

static int x1 has internal linkage, meaning it's only accessible by name from the translation unit it's defined in (this cpp file). If this line is in a header file, every file that includes the header will get its own copy of the variable.

int x2 has external linkage, meaning another translation unit (cpp file) could have extern int x2; in global scope and access the variable. If this line is in a header file, and multiple files include the header, you're violating the One Definition Rule since the variable is being defined once per include. You must instead use extern int x2; in the header, and then in a single cpp file have your int x2 = ...; to avoid multiple definitions.

See https://en.cppreference.com/w/cpp/language/storage_duration

Related