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 {
    MESSAGE
}

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

Why?

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
testlib-b418ecfc56bd155d.testlib.9xj4bveb-cgu.0.rcgu.o
rust.metadata.bin
testlib-b418ecfc56bd155d.testlib.9xj4bveb-cgu.0.rcgu.bc.z
/target/release$ mkdir contents
/target/release$ cd contents/
/target/release/contents$ ar x ../libtestlib.rlib
/target/release/contents$ grep someverylongstringsthatmakeupmultipleMB --text --only-matching *
rust.metadata.bin:someverylongstringsthatmakeupmultipleMB
testlib-b418ecfc56bd155d.testlib.9xj4bveb-cgu.0.rcgu.o:someverylongstringsthatmakeupmultipleMB

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!