rust-lang / rust-lang/cargo

How should dynamic linking work in Rust?

Open
#3,573 11 comments 14 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-linkage C-feature-request S-needs-design
Dominant language
Rust
Stars
15.5k
Forks
3k
Avg merge
23h 30m
Merged PRs (30d)
51

Description

If I set crate-type=["dylib"] in Cargo.toml, I would expect it to not only compile the top-level crate as dynamic, but also all its transitive dependencies, and link with them dynamically (ie, with -C prefer-dynamic semantics).

Right now if you try this, it builds all the dependencies as static, and statically links them into the dynamic crate it builds. If this dynamic crate is subsequently used to build an executable with a diamond dependency graph (ie two of its dependencies have the same transitive dependency), rustc fails because of the crate that's duplicated by being linked into two other dynamic crates. This happens most often with libstd, but it can happen with any shared dependency. This suggests that the default for any dynamic crate should be "prefer dynamic" for its dependencies, since the current default is only useful in very niche cases.

If you specify -C prefer-dynamic as a build flag, then it will not include the dependent crates in the dynamic output - but it also won't build the dependencies at all.

Further, if you specify crate-type=["dylib", "rlib"], I would like it to build the crate twice as static and dynamic (this does work currently), and all its dependencies (this does not).

Related: #3408

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Cargo.toml crate-type setting and the -C prefer-dynamic build flag, then trace how each affects transitive dependencies and diamond dependency graphs. Compare the dylib, rlib, and combined dylib/rlib cases described here. Done means the intended dynamic-linking semantics are defined and implemented consistently without duplicate shared dependencies.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
build-system, tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.