ollien
ollien

Reputation: 4766

Linking against binary crate

There's a crate I want to use as a library for some of my own code (speedtest-rs specifically, but it doesn't really matter). However, whenever I try to use this crate, the compiler doesn't want to play nice with it.

$ cargo build
   Compiling my-project v0.1.0 (/home/nick/Documents/code/my-project)
error[E0432]: unresolved import `speedtest_rs`
 --> src/main.rs:1:5
  |
1 | use speedtest_rs::*;
  |     ^^^^^^^^^^^^ use of undeclared type or module `speedtest_rs`

Looking at the Rust book, it seems like there's a distinction between a binary and library crae

The rand crate is a library crate which contains code intended to be used in other programs

Some googling has shown me that binary crates just have an extra link step, so I should be able to link against them, right? I know a lot of Rust packages have both a library and a binary in them, but what do you do when an author does not seem to follow this pattern?

Upvotes: 1

Views: 681

Answers (1)

mcarton
mcarton

Reputation: 29981

Some googling has shown me that binary crates just have an extra link step, so I should be able to link against them, right?

No. It's not that simple. Plus that extra step creates an executable file rather than a library file. An executable cannot be used as a library.

I know a lot of Rust packages have both a library and a binary in them, but what do you do when an author does not seem to follow this pattern?

You can:

  • Ask them on GitHub to publish a library.
  • Fork the crate and make your own library (which you can do since it is published with the usual dual “Apache License, Version 2.0” + “MIT” license).

There isn't an automated way to use a binary crate as a library because in particular:

  • Rust won't generate a library.
  • Since the crate is missing a src/lib.rs file, nothing is exported. This is akin to have all items in that crate private. You wouldn't be able to use anything.

Upvotes: 4

Related Questions