I have a dprint function, that basically only does println!("{:?}", self). The reason for it is, that one can't println!() in GDB, so, I want to be able to at least be able to do my_struct.dprint() (for debug print). However, Rust evidently, admittedly correctly, sees that dprint() is never used in the binary and keeps removnig it, how can I stop that?
I have lto="off", debug=true, opt-level=0 and it is still getting removed.
It’s better to think of it as “not added” rather than “removed”. Machine code is generated when it is known to be needed, so you need to give rustc a reason to include it.
As far as I know, the most practical way to do this is to add the #[unsafe(no_mangle)] attribute, which in addition to its effect on symbol mangling, also makes the symbol public (even in a binary) and thus makes it required to exist. I’m not aware of a way to force a function to be included without any other effects on it, unfortunately.
To be clear, one can call my_struct.dprint() in GDB when it is in the binary, no demangling needed. (I just put it in the first line in main, but I would prefer not to do this for all my structs)
You can instead use the export_name attribute to give them different names: it should work the same other than not inferring the name, though those docs imply you might also want the used attribute?
I vaguely recall creating a const-pointer to the thing to force the linker’s hand. Unfortunately, that was more than a year ago so I don’t recall the details.
'dyn' does not do what you think it does. In your case the function would likely not be callable at all without causing UB.
What 'dyn' actually does is it collects for each compilation unit (possibly even at a smaller scale idk) all call/usage sites to a specific dyn Trait, and then constructs a v-table only and exclusively only for those types. That means if you just export a function with a dyn {Trait} argument and you never call this function nor use that same dyn {Trait} anywhere else in your crate, you can be rest assured, that not a single v-table was created. With other words the only type that is coercible to your dyn {Trait} is ! (the Never type), and as the Never type is not uninhabited, this means similarly your dyn {Trait} is uninhabited, i.e. no valid values exist for &dyn {Trait}, any value would be UB, thus calling the function would always be UB