So, I know that in C ++ constants, by default, a different relationship is used than variables. Therefore I should not set
int foo;
in some heading - the linker will rightly complain about several definitions . OTOH, I can write
const int bar = 42;
in the header, and the compiler ensures that there is only one definition of bar .
It is easy to understand with integral constants how the compiler deals with this - at least until no one takes the address of bar or does some other fun thing that requires an assignment for storage). However, what if someone does this? And what if it's not an integral, but something that is needed to execute the code at runtime? Suppose I put this in the header:
const std::string baz = "h2g2";
Assuming a slight string optimization, this requires dynamic memory allocation at runtime, so the code must be executed, the address must be stored somewhere, etc.
I assume that in the end I get one definition of baz per translation unit, only the compiler assigns it an internal binding to prevent the linker complaining? Or am I missing something?
Note. I'm not interested in constexpr , just in plain old C ++ constants, since they existed from the 80s and were codified in C ++ 98. (However, if a comprehensive answer would include how it all fits with constexpr , I would not complain about it.)
c ++ constants c ++ 98 linkage
sbi
source share