static has a bunch of different meanings in C/C++.
zig is no different than C or C++ is far as that is concerning, you just define and reference them a little different.
vars (in all c++/c/zig) all have two properties: lifetime and scope. Lifetmie is how long the variables exists and scope is where it can be accessed from. They are pretty related most of the time.
global usually refers to scope in that it can be accessed from anywhere. static refers to lifetime covering the entire program. so all globals are static, but think of a static variable in a function in c/c++. It can only be accessed while in the function (function scoped), but between invocations it still is there and doesn’t go away. top level variables in c/c++ are global but since C and c++ have obj and so (dll) files the link/loader has to get involved and get into this whole complex subject of symbol exports so let’s just dodge that and not speak of them ever again. (zig only has one translation unit so there isn’t really the same thing in zig).
Here’s the C/C++ and Zig equivs.
c++ class statics and zi struct statics are both per type and not per instance, to basically the sae:
class Cls {
public:
int instance_var;
static int x = 0;
void inc() { x += 1; }
// or void inc() { Cls.x += 1; }
// or void inc() { this->x += 1; }
};
const Cls = struct {
instance_var: u32,
var x: u32 = 0;
pub fn(this: @This()) void { x += 1; }
// or pub fn(this: @This()) void { Cls.x += 1; }
// NOT this.x
};
function scope static need to be wrapped in a stuct – every static needs ot be wrapped in a struct. Structs in Zig are also the namespace feature, so you make a struct with a static - the same as above.
void cfunc() {
static int x = 0;
x =+ 1;
}
fn zfunc() void {
var s: struct { var x: u32 = 0 };
s.x += 1;
}
that brings us to file scoped. Since a file is a namespace, that means its actually a struct too. you can imagine the entire file being wrapped in a struct named the same as the file minus the extension. So it looks like a struct static.
static int x = 0;
// prentend the entire file is wrapped in a struct { ... }
var x: u32 = 0;
C and C++ have some added complexity with static basically being a linker instruction (inline in c++ is the same way - it mean emit weak symbol and no longer affects inlining - fun huhh).