Why Rust has name mangling

why this have to be done?

Take, for example, a program like this:

struct One;

struct Two;

impl One { fn foo() { ... } }
impl Two { fn foo() { ... } }

Now there are two functions named foo. But for historical reasons, each function is labeled with a single string for its name (in object files, executables and libraries, etc.). This string must be unique across all names in the entire program, including dependencies.

So rustc gives each function a different name by "mangling" foo into something like _ZN7example3One3foo17h16fcc82fa6043ccbE. Notice how the mangled name includes the crate name ("example"), the type and/or module the function is associated with ("One"), the bare name itself ("foo"), and a hash.

This means you can have a different foo for every combination of crate, module, type, and crate version, without collisions.

2 Likes

how can you make sure that they never collide?

shouldn't this be handled by the linker?

The linker has no idea about Rust. It only knows about C, where functions with identical names collide. Even C++ requires name mangling to work around this. In fact the Rust name mangling is derived from the C++ one.

4 Likes

In the fully general case, you can't. Making it possible is one of the reasons why C/C++/Rust/etc typically require you to build all libraries in an application using the same toolchain.

[Moderator note: It would help a lot if you can provide some context with your questions, like what problem you are trying to solve or what code you are working on. On this forum in particular, posts should mostly be focused on specific changes to the Rust language/implementations/infrastructure.]

10 Likes

The Rust mangling format is defined by RFC 2603, which also answers a lot of questions about its design and motivation:

https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html

7 Likes