Global variables should generally be avoided, because they are available everywhere. It is difficult to understand where they are modified and used. However, if you really need them:
// header, or source (add static)
constexpr int x = 0;
Use const
for non-literal types.
?inline
// header
extern int x;
?inline
// source
int x = 0;
// header only, use static in source
inline int x = 0;
?inline
Use static
or an unnamed namespace for any
globals that are TU-local (used only in one cpp file).
?inline
If you put int x = 0;
into a header, you may get linker errors.
x
is extern
by default, so the linker would see multiple conflicting definitions when the header is included in
multiple source files.
<:cppreference:875716540929015908> Storage class specifiers