炸鱼薯条德里克
炸鱼薯条德里克

Reputation: 999

How to use external crates in a Cargo build script?

I have this file structure

Test
│   .gitignore
│   build.rs
│   Cargo.toml
│
├───.vscode
│       tasks.json
│
├───src
│       main.rs

I have this Cargo.toml

[package]
name = "test"
version = "0.1.0"
authors = ["xtricman"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
regex = "*"

I have this build.rs

fn main() {
    let mt = regex::Regex::new(r"_[1-9][0-9]+.rs|_0.rs\z").unwrap().find("gdf_980.rs");
    let mts = if mt.is_some() {
        println!("{}", mt.unwrap().as_str());
    } else {
        println!("None");
    };
}

I want to use the regex crate in my build script, but I get a compile error

error[E0433]: failed to resolve: use of undeclared type or module `regex`
 --> build.rs:2:14
  |
2 |     let mt = regex::Regex::new(r"_[1-9][0-9]+.rs|_0.rs\z").unwrap().find("gdf_980.rs");
  |              ^^^^^ use of undeclared type or module `regex`

Does Cargo only support std in build.rs?

Upvotes: 16

Views: 5514

Answers (1)

Shepmaster
Shepmaster

Reputation: 430290

Add the crate to your [build-dependencies] key:

[build-dependencies]
regex = "*"

You can also add the crate to the [dependencies] key if your crate needs it.

See also:

Upvotes: 25

Related Questions