Unable to do LTO on Windows

I followed the step in the book on Windows11, and failed with link error:

fatal error LNK1107: invalid or corrupt file: cannot read at 0xF7E

Clang and Rustc:

clang-cl --version

clang version 18.1.6
Target: x86_64-pc-windows-msvc
Thread model: posix
InstalledDir: D:\LLVM\bin

rustc -V --verbose


rustc 1.80.0-nightly (bdbbb6c6a 2024-05-26)
binary: rustc
commit-hash: bdbbb6c6a718d4d196131aa16bafb60e850311d9
commit-date: 2024-05-26
host: x86_64-pc-windows-msvc
release: 1.80.0-nightly
LLVM version: 18.1.6

plus.c:

int plusone(int x) {
    return x + 1;
}

build.rs:

fn main() {
    use std::env::set_var;
    set_var("CC", "clang-cl");
    set_var("CXX", "clang-cl");
    set_var("CFLAGS", "/clang:-flto=thin /clang:-fuse-ld=lld-link");
    set_var("CXXFLAGS", "/clang:-flto=thin /clang:-fuse-ld=lld-link");
    set_var("AR", "llvm-lib");
    cc::Build::new()
        .file("plus/plus.c")
        .opt_level(3)
        .compile("plus");
}

If I remove the -flto there will be no error but I need the optimization.
Is it a bug on rustc or llvm ?

1 Like

Are you specifying

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

in .cargo/config.toml? Msvc's link.exe doesn't know how to handle LLVM bitcode. You have to use LLVM's lld-link.exe instead. Also make sure to pass -Clinker-plugin-lto to rustc if you want the Rust and C code to be LTOed together. If you don't pass it the Rust code and C code will be LTOed separately (assuming you actually enabled LTO for the Rust code in the first place).

1 Like

Thank you, it works for me.

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.