If I have the following in a header file:
Foo.h
Foo
{
public:
static const int BAR = 1234;
...
};
Do I also need to define the variable in the .cpp, e.g.:
Foo.cpp
const int Foo::BAR;
We have an issue where initializing a static in a header seems to work on MS compilers but with gcc on the Mac it seems to give linker errors.
You need both the declaration and the definition, just as you’ve written them.
Since it is an integer, you can initialise it in the declaration as you’ve done, and the compiler should treat it as a compile-time constant when it can. But it still needs one (and only one) definition in a source file, or you’ll get link errors when it can’t be treated as a constant.
Apparently, Microsoft decided that the standard behaviour was too confusing, and “extended” the language to treat a declaration with an initialiser as a definition; see this issue. The result is that you get link errors (multiply defined symbols) if you also define the symbol correctly. You can get the standard behaviour by disabling language extensions (
/Za).