Library Artifact(lib.rs)

We can create a library crate and then use it from one or more binary crates
Library is mainly about code organization and reuse; it does not automatically make the final executable smaller.

Create Library

$ cargo new mathlib --lib
mathlib/
├── Cargo.toml
└── src/
    └── lib.rs

$ lib.rs
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
pub fn multiply(a: i32, b: i32) -> i32 {
    a * b
}

$ cargo build
target/debug/
└── libmathlib.rlib
      
Create an application that uses it

$ cargo new myapp
myapp/
├── Cargo.toml
└── src/
    └── main.rs
$ Cargo.toml
[dependencies]
mathlib = { path = "../mathlib" }

$ main.rs
use mathlib::{add, multiply};
fn main() {
    println!("{}", add(10, 20));
    println!("{}", multiply(10, 20));
}
$ cargo run
            

Types of Libraries

C++ Static(.a), Dynamic(.so) Libraries
In Rust 3 types of libraries can be created:

1. Rust-specific static dependency(.rlib) 2. staticlib(.a) 3. Sharedlib(.so) 4. Rust-to-Rust dynamic linking
Cargo.toml

[lib]
crate-type = ["rlib"]
            

[lib]
crate-type = ["staticlib"]
            

[lib]
crate-type = ["cdylib"]
            

[lib]
crate-type = ["dylib"]
            
Code

            


            

$ src/lib.rs
#[unsafe(no_mangle)]        //So that other languages can call it
pub extern "C" fn add(a: i32, b: i32) -> i32 {
    a + b
}
$ cargo build --release
target/release/
└── libmathlib.so