4
votes

There is a 3rd party C library that I'd like to link to in my Rust project. It is hosted on github and compiles only as a static library. Is there any way to have Cargo fetch this dependency for me? I'm thinking there isn't. I tried adding it as a dependency and got a "Could not find Cargo.toml in ..." error.

As an alternative, I thought of modifying my build.rs file to use the git2-rs crate to download a tag of the library, possibly specified as a tag name passed through an environment variable.

Another option would be to include the source of the C library in my project, but I was thinking if the users of my crate want to use a different (but compatible) version of the 3rd party library with my crate, they wouldn't be able to do so as easily.

So how are others in the community handling situations like this?

1

1 Answers

9
votes

In general, you want to create a libfoo-sys crate. That crate will have a build script that compiles the native library and sets up the linker options.

The build script can use build-time dependencies like the cc crate to make the process of downloading and compiling the native library easier.

You can use environment variables or features to choose where the native library comes from. You could use one already installed by the user by their system package manager (or perhaps a hand-compiled version), you could download the source from somewhere, you could include the code in the repository, or you could use a git submodule to reference another git repository instead of actually copying code.

In many cases, you will also use a tool like rust-bindgen to create the "raw" Rust bindings for the C library.