<p>What is the best way to initialize a private, static data member in C++?  I tried this in my header file, but it gives me weird linker errors:</p>

<pre><code>class foo
{
    private:
        static int i;
};

int foo::i = 0;
</code></pre>

<p>I'm guessing this is because I can't initialize a private member from outside the class.  So what's the best way to do this?</p>

The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h
```
```
class foo
{
    private:
        static int i;
};
```
```
But the initialization should be in source file.
File: foo.cpp
```
```
int foo::i = 0;
```
```
If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.
The initialisation of the
```
static int i
```
must be done outside of any function.
Note:
Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of
const integer type
(
```
bool
```
,
```
char
```
,
```
char8_t
```
[since C++20],
```
char16_t
```
,
```
char32_t
```
,
```
wchar_t
```
,
```
short
```
,
```
int
```
,
```
long
```
,
```
long long
```
, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.
). You can then declare and initialize the member variable directly inside the class declaration in the header file:
```
```
class foo
{
    private:
        static int const i = 42;
};
```
```