Compilation - what's happening?

Hello. I am learning Rust, and have a question about compilation. I have Rust installed.

When I tried to compile (cargo run) the default "Hello world" program that cargo produces as default code, it failed with error message "Error: linker link.exe not found". A bit of work with Google told me to run

rustup toolchain install stable-x86_64-pc-windows-gnu
rustup default stable-x86_64-pc-windows-gnu

This is enabling the mingw C++ compiler. But I always thought that Rust uses the LLVM compiler. What is happening, please?

The MSVC toolchain uses the Visual Studio C++ linker, and it doesn't look like you have that installed (either that, or it's not on your PATH).

You can obtain the linker by installing the Visual Studio C++ build tools (specifically the MSVC and Windows SDK components).

On the GNU toolchain, it uses the mingw linker instead.

1 Like

Thank you for your reply. That explains the error message,

When I Google rust llvm the impression that I get - I think most people would get - is that Rust uses LLVM. But it does its own compilation and uses an external linker, which it borrows from elsewhere.

What is the connection please, if any, between Rust and LLVM?

I don't understand what you mean by that. The Rust compiler emits LLVM IR based on the Rust code, and then LLVM takes over and generates actual machine code based on the LLVM IR. How much it counts as "own" compilation in your definition, I'm not sure – certainly, rustc performs a large amount of work with regards to type checking and inference, intermediate representation optimization, and LLVM codegen. And then LLVM itself performs another big bulk of work for code generation, instruction selection and scheduling, peephole optimization, etc.

Well, I'm not sure that's a correct thing to say – a linker is pretty much language-agnostic by definition, so compilers don't usually need to come with their own linkers. Generally, there is one linker (or maybe 2 or 3 of them, e.g. if you have installed both the GNU and the LLVM linker on your system, or on Windows you are using the MSVC and the GNU linker as well), and every language that compiles to platform-native machine code in a supported file format can just use that linker. It would be useless and excessive to reinvent the wheel and write a separate linker for every language.

Pretty much same between C and LLVM. On Windows to compile C program you can use either MSVC or Clang. On Linux you can use GCC, ICC, Clang or some other compilers. The Clang uses LLVM underneath as optimizer and code generator.

The rustc currently has single code generator backend which uses LLVM underneath on the stable release. Other codegen backends, namely GCC and Cranelift, are usable in many cases but needs more polishing to be included to the stable release.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.