Dude! Where's my string constant?
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Tue Jan 23 13:26:38 PST 2007
kris wrote:
> Does D have a compile-time string constants? One that doesn't wind up in
> the obj file when it is unused?
>
> const char[] Foo = "foo";
>
> Apparently resides in the object file, used or not. Just like const int
> does. For true compile-time integer constants, we're supposed to use
> enum -- but what of strings? Enum currently doesn't like char[] :)
>
> Suggestions for faking it include:
>
> * char[] Foo() { return "foo"; }
Only works if *no* string constant in the module is used. They're all
put into .rodata, which is only thrown away if it's not referenced *at
all*.[1]
> * template Foo { const Foo="foo"; }
This string will not be created until Foo is instantiated, and is put
into a separate linkonce section (which can be removed if unused)[1].
Good find :).
Note: this won't happen if the member is declared char[], it needs to be
the (automatically-deduced) static array.
> The former *should* get removed by the linker as unused, while the
It isn't necessarily, as noted above.
> latter apparently gets eliminated by way of lack-of-expansion.
Yep.
> However, going to these lengths is surely counter-intuitive?
Yes it is. What happens for the second one when instantiated should
really happen by default for all strings (i.e. be put into separate
sections).
[1]: Usual disclaimer: on Linux, using ld --gc-sections. I know not of
OMF & optlink :P.
More information about the Digitalmars-d
mailing list