Static keyword
...

In C++, the static keyword has several different uses, depending on where it is used.

When used with a variable or function in global scope, static restricts the variable or function's scope to the current translation unit, which is the source file being compiled and any files included directly or indirectly by that file. This means that the variable or function cannot be accessed from other translation units. For example:

// file1.cpp
static int x = 5;
static void foo() { /* ... */ }

In this example, x and foo() are declared as static variables and functions in the file1.cpp translation unit. They cannot be accessed from other translation units unless they are explicitly declared as extern.

When used with a variable or function in a class or struct, static indicates that the variable or function is shared by all instances of the class or struct, rather than being associated with individual instances. For example:

class MyClass {
public:
  static int x;
  static void foo() { /* ... */ }
};

int MyClass::x = 5;

In this example, x and foo() are declared as static members of the MyClass class. x is a shared variable that is associated with the class rather than individual instances of the class. foo() is a shared function that can be called on the class itself, rather than on individual instances.

When used with a local variable inside a function, static indicates that the variable retains its value between function calls, rather than being reinitialized each time the function is called. For example:

void foo() {
  static int x = 5;
  x++;
  std::cout << x << std::endl;
}

foo(); // prints 6
foo(); // prints 7
foo(); // prints 8

In this example, x is a static local variable inside the foo() function. It retains its value between function calls and is incremented each time the function is called.

Overall, the static keyword is a useful tool for controlling the scope and lifetime of variables and functions in C++. By using static, you can make your code more modular, efficient, and easier to maintain.

now imagine we have 2 global variables in 2 cpp files with one name this will result in a linking error unless one of them is static which then the static variable becomes kinda local and the other cpp files can't see it OR we can use the keyword extern which means external linkage. this means that if we do both of them we get an error cause the extern looks for our variable outside but cause it is static it cant find the variable.
all the things I said in above paragraph is the same for functions.

  • so you should use static as much as you can if you don't want them to be linked across translation units its basically why you use private in classes