rust-lang / libs-team

The home of the library team
Apache License 2.0
127 stars 19 forks source link

Windows MSVC CRT linking #211

Closed ChrisDenton closed 6 months ago

ChrisDenton commented 1 year ago

Proposal

Problem statement

With the windows-msvc targets, linking the C runtime can have a number of different configurations. For example, linking the CRT libraries compiled with debug symbols. However, currently the libc crate (when compiled as a dependency of std) does not allow this. It hardcodes a choice of only two configurations (static or dynamic), controllable with the target-feature compiler flag.

Motivation, use-cases

When integrating with C/C++ code, it's essential that the same CRT is used for the Rust parts as the C/C++ parts. Mixing CRTs is unsupported. Currently this requires ensuring the C/C++ part of the build to match Rust. The cc crate can take care of automatically selecting the static or dynamic CRT but this means it can't offer to use debug libraries or other CRTs (because they would be incompatible with Rust).

Even in a pure Rust build, linking the debug CRT may be useful for debugging.

Solution sketches

Add a cfg option to the libc crate so that when compiled with rustc-dep-of-std the right CRT can be selected. Users can then set rustflags in config.toml to set the options for a build.

[target.'cfg(all(windows, target_env="msvc"))']
rustflags = [
    "-C", "target-feature=+crt-static",
    "--cfg", 'msvc_crt_link="debug"',
]

This cfg can also be detected in build scripts using CARGO_CFG_MSVC_CRT_LINK so that crates such as cc can adjust other native builds accordingly. Options include "debug" for linking the debug CRT the and "nocrt" for taking manual control of linking the CRT (essentially equivalent to using nostd).

Links and related work

What happens now?

This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.

danakj commented 1 year ago

AIUI this proposal would be sufficient to allow Debug Windows builds of rustc-linked targets in the Chromium project.

As we build the stdlib separately for release or debug configurations, and the choice applies to all build targets, the choice of CRT when building stdlib would allow us to link C++ into Rust.

ChrisDenton commented 6 months ago

Linking other CRTs is now possible as the CRT is linked using /DEFAUTLIB (in latest nightly) so it's easy to disable (e.g. using /NODEFAULTLIB:msvcrt) and then override. I feel that's sufficient for build systems to set their own CRT even if not the most ergonomic.

Rust having more built-in options would be nice but it's not something I have the bandwidth to pursue atm. If someone else wants to then I can reopen (or feel free to make a different proposal).