Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Bo Persson Newsgroups: comp.lang.c++ Subject: Re: Global const objects missing from object file Date: Sun, 10 Oct 2021 10:34:08 +0200 Lines: 55 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net knWIzsYZafW6S0hL5UbewQoPNg7KxzB+1AYYov49cHwad+Fh5n Cancel-Lock: sha1:wYaK9px1gCDMlNkEs7yx3S4RXJo= User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Thunderbird/78.14.0 In-Reply-To: Content-Language: sv Xref: csiph.com comp.lang.c++:81959 On 2021-10-10 at 08:55, Steve Keller wrote: > Paavo Helde writes: > >> Such global const definitions normally appear in a common header file >> and would just cause duplicate linker symbols if they had external >> linkage. Now they can be just optimized away in translation units >> which do not use them. >> >> I believe the original motivation was to have an easy replacement of C >> macros in header files, i.e. instead of >> >> #define a 42 >> >> one can easily use >> >> const int a = 42; >> >> which would function almost exactly like a #define, plus it honors C++ >> namespaces and cannot be undefined. > > If you write such "global" const objects into a header file they are > in fact not global, because the implicit 'static' makes them local to > file translation unit and this can even cause duplication: > > $ cat foo.hh > const int a = 42; > > const int *bar(); > $ cat x.cc > #include "foo.hh" > > const int *bar() { return &a; } > $ cat y.cc > #include > > #include "foo.hh" > > const int *foo() { return &a; } > > int main() > { > std::cout << (void *)foo() << '\n' << (void *)bar() << '\n'; > } > $ g++ -Os -o foo x.cc y.cc > $ ./foo > 0x56027d731008 > 0x56027d731004 > > For a small 'int' one may not care but for larger constant objects > this may be really bad. > It only causes duplication if you take the address and return a pointer. Why do that for a constant defined in a header?