Prevent Const Promotion

I have a static string that I would like to show up in my binary's symbol table. I have marked it with #[no_mangle] and use it in one location, but it doesn't show up in the symbol table. I can confirm that it is being included by running strings <binary> | grep "<contents of static>".

If I instead don't use it in my own code and just mark it with #[used] then it does show up in the symbol table. This leads me to assume that the static is being promoted to a const and effectively inlined. If this is correct, how can I prevent it from being promoted or optimized out?

I've been able to work around this by creating a separate const fn that is used in the code and to set the static. The static is just marked as #[used]. This doesn't seem like a proper solution, but it works for now.

I’m not an expert in codegen and linking behavior, but this sounds to me like possibly a bug in no_mangle/used, rather than something there is a different correct way to do.

1 Like

Try creating a const pointer to it. That worked to keep the optimizer from removing a function. It should also work for data.