So I was reading section 3.2 (One definition rule section) in the latest working draft of the C++ standard and came across this:
Every program shall contain exactly one definition of every non-inline
function or variable that is odr-used in that program; no diagnostic
required.
This struck me as strange with regard to the variable part, because if a header file has a global constant variable and function like so:
const int k = 10;
int foo(const int &i) {
return 0;
}
What if you mistakenly call foo(k)
? It seems like this would result in UB because k
has internal linkage (i.e. every translation unit would have its own definition of k
, so there wouldnt be exactly one definition … in that program). So basically if you have any const
variable with global scope you'd have to remember not to call any functions which take its reference or address.
Best Answer
The one definition rule in the standard is not "appear" only once, but that they have only a single definition. E.g. if the
const
were in a header file, it could appear in multiple translation units, yet they would all have the same single definition. As an aside, the linker could then fold them all into a single location (if a location is even required).There would be no undefined behavior here. The internal linkage is fine, it is
const
and there is only a single definition of it.This (the
const int i = 1234;
) has a general use case for program wide constant values, e.g.const double pi = 3.1415
,const std::size_t answer = 42;
etc.On a side note, you have specifically asked about the global variables, but placing constants and the like into namespaces are always a good way to avoid name clashes etc.