5. Building a library

This chapter describes how to build a library using rustc.

The examples in this chapter assume the following directory structure:

.
└── rust_library
    ├── addition_ops.rs
    ├── multiplication_ops.rs
    └── ops.rs

We are going to build a library consisting of simple arithmetic operations. Source file ./rust_library/addition_ops.rs contains:

pub fn add(left: i32, right: i32) -> i32 {
    left + right
}

pub fn sub(left: i32, right: i32) -> i32 {
    left - right
}

Source file ./rust_library/multiplication_ops.rs contains:

pub fn div(left: i32, right: i32) -> i32 {
    left / right
}

pub fn mul(left: i32, right: i32) -> i32 {
    left * right
}

pub fn rem(left: i32, right: i32) -> i32 {
    left % right
}

We can bundle the two source files into a convenient single library by supplying a special source file called a crate root module. Crate root module ./rust_library/ops.rs contains:

pub mod addition_ops;
pub mod multiplication_ops;

The outline modules cause the source files that correspond to the module names to be inlined within the crate root module.

To create the library, run:

$ rustc --edition 2021 --crate-type lib ops.rs

If you are using CriticalUp, you can use criticalup run in front of the command to invoke the project’s Ferrocene toolchain once installed.

Note

Depending on the compilation target you want to use, you might need to pass additional flags to rustc. Please check the “Required compiler flags” section of your target’s page.

This invocation produces library file libops.rlib.

The compiler is capable of producing different kinds of libraries, such as static, dynamic, and native libraries. To do so, consult the documentation of compiler argument --crate-type for further details.