Why do rust libs contain strings twice?

When I have a very simple library like (lib.rs):

static MESSAGE:&str = "someverylongstringsthatmakeupmultipleMB";

pub fn hi() -> &'static str {

then the string appears twice in the .rlib file, as can be seen with:
cat target/release/lib*.rlib|grep someverylongstringsthatmakeupmultipleMB --text --only-matching


1 Like

rlib are archive files with metadata and with the code in two different formats: bytecode and architecture-dependent binary object

looks like the string is in both in the rust.metadata.bin and the .o, at least

/target/release$ ar t libtestlib.rlib
/target/release$ mkdir contents
/target/release$ cd contents/
/target/release/contents$ ar x ../libtestlib.rlib
/target/release/contents$ grep someverylongstringsthatmakeupmultipleMB --text --only-matching *

it's possible that if you manage to unpack the bytecode (bc.Z) there's even a third copy there

mind that only one will be linked to the final binary though

but if you want a more compact library, you could specify to generate a static or dynamic library instead of a rlib

1 Like

Thanks for the explanation!