Search code examples
c++c++11variablesglobal-variablesglobal

Global variable and static global variable


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()
{
...

Solution

  • 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.