Update 2 years later:
Every global accessible by more than one source file should be wrapped in an inline
function so the linker shares the object between the files, and the program initializes it properly.
inline std::string const &const1() {
static std::string ret = "hello, world!";
return ret;
}
The inline
function is implicitly extern
and may be wrapped in a named namespace or a class, if you like. (But don't use a class just to hold static members, as namespaces are better for that. And don't use an anonymous namespace as that would defeat the linker, and each source would see a different std::string
object.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…