I am compiling and building an example program using rust. I chose rustc
instead of cargo
for compiling because it being a simple personal test project. So far using rustc
for compiling and building executable worked fine but when I tried to add an external rand
package its giving me this error
1 | extern crate rand;
| ^^^^^^^^^^^^^^^^^^ can't find crate
This is the full code
extern crate rand;
use rand::Rng;
fn main() {
for x in 1..11 {
let random_number = rand::thread_rng()
.gen_range(1, 101);
println!("{} -> {}", x, random_number)
}
}
How can I add external packages and run with rustc
?
This is possible without Cargo, but you'll have to do what it normally does for you.
rustc
using the correct flags.rand v0.7.3
├── getrandom v0.1.14
│ ├── cfg-if v0.1.10
│ └── libc v0.2.66
├── libc v0.2.66 (*)
├── rand_chacha v0.2.1
│ ├── c2-chacha v0.2.3
│ │ └── ppv-lite86 v0.2.6
│ └── rand_core v0.5.1
│ └── getrandom v0.1.14 (*)
└── rand_core v0.5.1 (*)
rand
isn't too bad, with only 8 transitive dependencies (including rand
itself, not including duplicates). Still, you'll have to go to crates.io or github and download the correct version of the source for each.
Then comes compiling. The minimum you'll have to do to compile your own binary is rustc -L dependency=/path/to/dependency/dir src/main.rs
. But remember that you have to do this for each of the 8 dependencies, and all of those have their own external dependencies. You'll also need to figure out the right order to compile them.
Moveover, some crates have their own settings in their Cargo.toml
that have to be respected. Some crates even have a build script that needs to be compiled and run (libc
is an example in this dependency tree).
Alternatively, you could just put
[dependencies]
rand = "0.7.3"
in your Cargo.toml
and run cargo build
. Your choice. Cargo is one of the nicest things about Rust, so I suggest you use it.
P.S. To see what exactly cargo
is doing, run cargo clean
to remove any already compiled dependencies. Then run cargo build --verbose
(or cargo build -vv
if you're brave). You'll see all the flags that get passed to rustc
, scripts that get run and everything else.