After reading a lot of the questions regarding initialization of static variables I am still not sure how this applies to const
variables at namespace level.
Your first definition places path1
in each compilation unit that includes config.h
. To avoid this, don't define variables in header files. Usually you'd declare the variables in the header as extern
:
extern const std::string path1;
extern const MyClass myclass1;
and define them in a translation unit, e.g. config.cpp
:
const std::string path1 = "/xyz/abc";
const MyClass myclass1("test");
Sometimes you need a constant variable that is usable only from one translation unit. Then you can declare that variable at file scope as static
.
static const std::string path1 = "/xyz/abc";
static
is not deprecated any more. static
and extern
are sometimes implied, but I always forget where and how, so I usually specify them explicitly for all namespace-level variables.