inline variables & Meyer Singleton
If we want to share a variable between multiple .cpp
files we could do the following:
//.h: extern int a; //.cpp int a = 1;
But this could be a bit messy, what if we wanted a header-only approach? This solution is called the Meyer’s Singleton approach:
//.h: inline int& Instance() { static int x = 1; return x; }
Now, since C++17 we have a better solution, leveraging the inner workings to the compiler.
inline int x = 1;
We also had the same problem pre-C++17 in structs and classes:
//.h: struct S { static int x; }; //.cpp: int S::x = 1;
Now we can just do:
struct S { inline static int x = 17; };
Source: https://vorbrodt.blog/2022/08/31/inline-not-what-it-used-to-be/