If I have a header foo.h
which contains
#ifndef FOO_H_
#define FOO_H_
namespace foo {
constexpr std::string_view kSomeString = "blah";
}
#endif // FOO_H_
then is it safe to include foo.h
from within multiple .cc
files in a single program, regardless of what they do with the symbol kSomeString
, or are there some uses that could cause an ODR violation?
Also, is it guaranteed that kSomeString.data()
will return the same pointer across .cc
files?
I'd like specific references to wording in the C++ standard if possible. Thanks!
Merely including
foo.h
from multiple translation units will not violate the ODR. However, indeed, there are some uses ofkSomeString
that will violate the ODR. See here for details and standard wording: https://stackoverflow.com/a/34446445It is not guaranteed that
kSomeString.data()
will return the same value in all translation units because it is not guaranteed that the string literal"blah"
is the same object in all translation units. According to [lex.string]/16,In C++17, the potential ODR violations can be prevented by defining
kSomeString
to beinline
. This will give it external linkage and hence a single address throughout the program (see [basic.link]/3 and [basic.link]/4) and allow it to be multiply defined (see [basic.def.odr]/4). Obviously.data()
can then only return one possible value.