Static keyword - it's multiple meanings in C++
The keyword “static” has several different meanings in C++ in different contexts. It can be confusing so this document outlines three usages you are likely to see in our code base.
Static Variables In A Function
when a variable is defined as static its value persists between function calls. The output of bar()
in the following sample is 1 3
. If b
isn’t defined as static then the output would be 1 2
.
int FOOfoo (int a) {
static int b = 0;
return b + a;
}
void FOObar () {
int c = 0;
c = foo(1);
COLcout << c;
c = foo(2);
COLcout << c;
}
Static Function Declaration
You can use static to define a function to prevent it from being exposed by the C Linker outside of the this cpp file. This is useful if you want to create a local helper function in a CPP file and want to be sure that it doesn’t clash with another symbol in the application - i.e. collide with a function of the same name in a different cpp file - reduces the symbol table sizes generated by the linker.
static void FOObar() {
//Code to do cool stuff
}
Static Global Variable or Static Class Member
In this context using the static keyword means that there is a single instance of the variable for the entire application. The same applies to a static member of a class.
// This COLdll instance is global for the application.
static COLdll Library;
class FOObar{
public:
private:
static COLstring m_AppName; // Only one instance of variable for the entire application
};