Rust

Speed up Rust builds on Windows with MSVC LLD and Defender exclusions

A clean cargo build on a mid-sized Rust project on Windows can take three times longer than the same build on Linux running on identical hardware. Incremental builds feel sluggish, cargo check stutters, and the fan spins up while the compiler spends most of its time waiting on disk I/O and linkers.

The Bottleneck: Linker Latency and Defender Overhead

On Windows, the default Rust setup leaves two major speed brakes enabled. The first is Windows Defender inspecting every .rlib, .rmeta, .obj, and .pdb file the compiler produces. The second is the default MSVC linker (link.exe), which does not parallelize symbol resolution and section merging as aggressively as modern alternatives.

Here is what an incremental build looks like when you change a single file in a workspace with 40 dependencies using the default MSVC toolchain without exclusions:

text
PS C:\projects\data-service> Measure-Command { cargo build }

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 18
Milliseconds      : 421
Ticks             : 184218320
TotalDays         : 0.000213215648148148
TotalHours        : 0.00511717555555556
TotalMinutes      : 0.307030533333333
TotalSeconds      : 18.421832
TotalMilliseconds : 18421.832

Eighteen seconds for a tiny leaf-crate edit is unacceptable during active debugging. Profiling with Windows Performance Recorder reveals two culprits: MsMpEng.exe (Microsoft Defender) locking newly created intermediate files under target\debug\deps, and link.exe taking 8 seconds on its own to lay out debug symbols in the final binary.

Toolchain Choice: MSVC vs GNU on Windows

Rust provides two ABI targets on Windows: x86_64-pc-windows-msvc and x86_64-pc-windows-gnu.

If you are developing software intended to integrate with the Windows ecosystem, run native debugging in Visual Studio or VS Code via cppvsdbg, or link against pre-compiled C/C++ libraries distributed via NuGet or the Visual Studio SDK, stick with msvc. The gnu toolchain relies on MinGW-w64. While it avoids the requirement to install the Microsoft Visual C++ Build Tools, it introduces severe friction:

  1. Debuggers: GDB on Windows is significantly less reliable than cdb or the VS debugging engine.
  2. C-runtime conflicts: Mixing MinGW runtime targets with native Windows dynamic link libraries often produces silent stack corruptions or CRT allocation mismatches.
  3. Linker ecosystem: You cannot use MSVC-compatible alternative linkers like lld-link or mold (via sold) easily on GNU targets without cross-compilation quirks.

Check your current default:

powershell
rustup default

If it says x86_64-pc-windows-gnu, switch it back to the native MSVC toolchain:

powershell
rustup default stable-x86_64-pc-windows-msvc

Verify that you have the Microsoft C++ Build Tools installed. You need the MSVC compiler toolset and the Windows SDK. If they are missing, install them via winget:

powershell
winget install --id Microsoft.VisualStudio.2022.BuildTools --exact --override "--passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended"

Neutralize Windows Defender on Cargo Artifacts

Defender inspects file handles synchronously by default when processes spawn rapidly. During a Rust compilation, rustc creates, closes, re-opens, and moves thousands of small files. Defender locks these files to inspect their headers, causing rustc to wait with ACCESS_DENIED retries or simple throughput starvation.

Do not disable your entire antivirus. Instead, apply targeted exclusions using PowerShell with administrative privileges.

First, identify your global CARGO_HOME and your project workspaces. If you use a single directory for all development (such as C:\projects), exclude that root, or exclude cargo.exe and rustc.exe processes directly. Process exclusions are safer and handle arbitrary build paths.

Run a PowerShell session with administrative privileges:

powershell
# Exclude the compiler executables from realtime scanning
Add-MpPreference -ExclusionProcess "rustc.exe"
Add-MpPreference -ExclusionProcess "cargo.exe"
Add-MpPreference -ExclusionProcess "lld-link.exe"

# Exclude the Cargo global cache directory
Add-MpPreference -ExclusionPath "$env:USERPROFILE\.cargo"

# Exclude your specific code directory
Add-MpPreference -ExclusionPath "C:\projects"

To confirm the exclusions are registered:

powershell
Get-MpPreference | Select-Object -ExpandProperty ExclusionProcess
Get-MpPreference | Select-Object -ExpandProperty ExclusionPath

If your IT department locks down Defender via Group Policy or Intune, Add-MpPreference will fail with an authorization error. In that scenario, move your project target directory to a Dev Drive formatted with ReFS, which supports trusted process optimizations natively and reduces filesystem overhead.

Swap link.exe for LLD

The stock MSVC linker (link.exe) is single-threaded in many of its critical stages. LLVM provides an alternative Windows-compatible linker called lld-link.exe. It accepts the same MSVC command-line arguments, writes standard PDBs that Visual Studio and VS Code can read, and links parallel crates far faster.

You can get lld in two ways: through the LLVM package directly, or by installing the llvm-tools component through rustup.

The cleanest approach on Windows is installing LLVM via winget so lld-link.exe lives on your system PATH:

powershell
winget install LLVM.LLVM

Restart your terminal, then verify it is reachable:

powershell
lld-link --version
text
LLD 18.1.8 (compatible with GNU linkers)

Now, configure Cargo to use lld-link instead of the default MSVC linker. You can do this per-project in .cargo/config.toml or globally in $env:USERPROFILE\.cargo\config.toml. Create or edit $env:USERPROFILE\.cargo\config.toml:

ini
[target.x86_64-pc-windows-msvc]
linker = "rust-lld.exe"
rustflags = [
    "-Z", "threads=8"
]

Wait: notice rust-lld.exe above instead of lld-link.exe. Modern Rust distributions bundle rust-lld.exe internally inside the toolchain directory. If you want to use the bundled one on the stable channel, configure the linker like this:

ini
[target.x86_64-pc-windows-msvc]
linker = "lld-link.exe"

If you installed LLVM via winget, lld-link.exe will be called. If you prefer to avoid third-party dependencies, you can force Cargo to use the internal rust-lld on stable Rust by passing this specific flag combination in .cargo/config.toml:

ini
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "linker=rust-lld"]

This avoids needing any external LLVM install. The rustc driver knows how to find its own shipped copy of LLD when passed -C linker=rust-lld.

Let us verify what linker is actually running during compilation. Run:

powershell
cargo clean
cargo build -v

Look at the final lines of the build output. You should see -C "linker=rust-lld" or the invocation targeting lld-link.exe.

Configure Faster Debug Formats

By default on Windows MSVC, rustc creates full PDB files containing complete type and symbol records. For debug iterations, this generates massive disk write volume.

Add split-debug settings to your workspace root Cargo.toml to tell the compiler to avoid packing debug info where it is not strictly necessary:

toml
[profile.dev]
split-debuginfo = "unpacked"

On Windows MSVC, split-debuginfo = "unpacked" leaves debug info in individual .obj files rather than spending link time consolidating everything into a multi-hundred-megabyte .pdb file. The MSVC debuggers (cdb, windbg, and the Visual Studio debugger) understand unpacked object records natively.

Gotchas and Real-World Failures

Gotcha 1: Unpacked PDBs and Remote Debugging or Path Changes

Setting split-debuginfo = "unpacked" drops incremental link time substantially, but it means your .pdb file no longer contains all the debug data. It merely holds pointers to the .obj files inside your target\debug\deps\ folder.

If you copy the resulting .exe and .pdb to another machine or another folder, the debugger will not show line numbers or local variable inspections. It will show assembly only:

text
Loaded 'C:\deploy\data-service.exe'. Symbols loaded.
(1ac4.364): Break instruction exception - code 80000003 (first chance)
*** WARNING: Unable to verify checksum for data-service.exe
data_service!main:
00007ff7`2d9a1000 4883ec28        sub     rsp,28h

If you need a standalone artifact to hand off to QA or upload as a build artifact, compile explicitly with the packed setting:

powershell
cargo rustc --profile dev -- -C split-debuginfo=packed # Or set it in [profile.release]

Or just rely on standard release profiles, which default to packed debug info when debug = true is set.

Gotcha 2: The C++ Run-Time Library Conflict (CRT Mismatch)

When linking external native libraries (like OpenSSL, zlib, or custom C++ code built via cmake-rs), you might see linker errors regarding symbol redefinition:

text
lld-link: error: duplicate symbol: __local_stdio_printf_options
>>> defined at libucrt.lib(local_stdio_options.obj)
>>> defined at msvcrt.lib(local_stdio_options.obj)

lld-link: error: defaultlib 'LIBCMT' conflicts with use of other libs; use /NODEFAULTLIB:LIBCMT

This happens when a third-party C/C++ dependency links against the static CRT (LIBCMT) while Rust’s default target config is linking against the dynamic CRT (msvcrt).

You can normalize your entire Rust build to use the static CRT by setting this in .cargo/config.toml:

ini
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]

Or, if your native libraries require the dynamic CRT, ensure you do not have conflicting static libraries pulling in LIBCMT. To tell lld-link to ignore the conflict explicitly during local debugging, pass the linker argument through rustflags:

ini
[target.x86_64-pc-windows-msvc]
rustflags = [
    "-C", "linker=rust-lld",
    "-C", "link-arg=/NODEFAULTLIB:libcmt.lib"
]

Verify the Results

Rerun the incremental benchmark after applying the Defender exclusions, setting linker = "rust-lld", and adding split-debuginfo = "unpacked".

Touch a single source file in your root crate:

powershell
(Get-Item src\main.rs).LastWriteTime = Get-Date
Measure-Command { cargo build }
text
PS C:\projects\data-service> Measure-Command { cargo build }

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 2
Milliseconds      : 104
Ticks             : 21045230
TotalDays         : 0.0000243579
TotalHours        : 0.000584589
TotalMinutes      : 0.035075383
TotalSeconds      : 2.104523
TotalMilliseconds : 2104.523

The turnaround went from 18.4 seconds down to 2.1 seconds. The CPU fans stay quiet, the disk avoids constant Defender read locks, and rust-lld finishes linking the binary in milliseconds.