Rustc-bin-link-arg and rustc-link-arg

The context for this thread is the pull request here: https://github.com/rust-lang/cargo/pull/7811

We at the Enarx project are writing low level code, including kernel-like things. We need to control linking arguments on things that aren't cdylib. I submitted a pull request implementing this feature.

Build scripts can already specify linker flags using rustc-cdylib-link-arg. I simply extended this to support rustc-bin-link-arg as well as rustc-link-arg (for either cdylib or bin). However, gathering broader input before merging such a feature seems wise.

Low level code needs access to the linker. No, it isn't portable. Yes, you can shoot yourself in the foot. But there isn't really any other way around it. Adding an option just for linker scripts isn't a good enough option because:

  1. Linker scripts don't work on all platforms.
  2. Linker scripts aren't portable.
  3. Access to other linker options is desirable.

The best option is to allow build.rs to make some intelligent choices based on which linker is in use. From here, utility crates (similar to cc) can attempt to build additional functionality on top of the raw primitives.

Thoughts? Comments?

4 Likes

Very much in favor. I would like to use this for size optimization options, to build tiny binaries.

I personally would like to have the option of writing linker options directly in Cargo.toml, for projects that know their linker. (Or, perhaps, in a target-specific section.) But I absolutely think build script support should come first.

1 Like

When Cargo insisted on portability of build scripts, I used to think "who cares about Windows!", but seeing it actually work nicely, I'm now in favor of keeping it working.

We have th cc crate to abstract away some of the MSVC vs GCC differences. Could something similar be done for linking?

I suggested exactly that in the penultimate paragraph of my original comment above. Unfortunately, linking is harder in general. For example, only some linkers support linker scripts. Those that do support completely different syntaxes and functionalities (with the exception of lld which intentionally copies GNU ld).

Once we have the raw primitive of specifying linker arguments, we can create a new crate which exposes a least-common denominator of features supported by all linkers. This would be useful for things like choosing which symbols to export.

However, low-level projects will still probably need to commit to a set of supported linkers for more direct control.

4 Likes