Search code examples
rustlinkerrust-cargo

rust libraries with cargo (rlib)


I am trying to create a library in rust to be used with rust executables. In C you can just create your .a or .so (or .lib or .dll on windows) and use tools like CMake to link everything, however rust does not seem to have this kind of infrastructure?

It is possible to make an executable with cargo (cargo new ) and create a library by adding the --lib flag (cargo new --lib), but then how would you use the resulting .rlib file (from the library cargo project)? I managed to link the .rlib file as follows:

rustc main.rs --extern foo=libfoo.rlib

and that works beautifully, though, I am not interested in writing a thousand rustc commands to build the final executable (which depends on the .rlib) if there is cargo that can do that for you. I tried working with a build script (which works perfectly for any C library, static or dynamic), but if I try it with the .rlib file, cargo says that it cannot find "foo" (-lfoo), the build script:

fn main() {
  println!("cargo:rustc-link-search=.");
  println!("cargo:rustc-link-lib=foo");
}

I tried replacing the path (search) to different directories (whilst also moving the .rlib file to the correct directory), also tried different combinations of libfoo, libfoo.rlib, ... (note that for the C libaries, foo is sufficient).

So my question really is: How can you create a rust library for private use, and how do you use it with a rust executable in a proper way, avoiding manual rustc commands? Are there tools that do this? Am I missing something in the build script? Perhaps there exists something like CMake for rust?

I suppose it is possible to just create a C interface over the rust code and compile another C project as that does work with cargo.

I do NOT want to publish the code to crates.io as I want this library strictly for private use.


Solution

  • Cargo does not support using pre-compiled .rlibs. Cargo is designed to compile programs fully from source (not counting native libraries).

    How can you create a rust library for private use … I do NOT want to publish the code to crates.io as I want this library strictly for private use.

    To use a private library, you write a dependency using a path or git dependency (or use a private package registry, but that's more work to set up).

    [dependencies]
    my-lib-a = { path = "../my-lib-a/" }
    my-lib-b = { git = "https://my-git-host.example/my-lib-b", branch = "stable" }
    

    Your private library is now compiled exactly like a “public” one.