Creating a Library

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will create a library called rary in Rust. The rary library contains a public function called public_function, a private function called private_function, and an indirect access function called indirect_access. Afterwards, we compile the library using the rustc command, resulting in a file named library.rlib.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"]) rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`") subgraph Lab Skills rust/function_syntax -.-> lab-99337{{"`Creating a Library`"}} rust/expressions_statements -.-> lab-99337{{"`Creating a Library`"}} rust/lifetime_specifiers -.-> lab-99337{{"`Creating a Library`"}} end

Creating a Library

Let's create a library, and then see how to link it to another crate.

In rary.rs:

pub fn public_function() {
    println!("called rary's `public_function()`");
}

fn private_function() {
    println!("called rary's `private_function()`");
}

pub fn indirect_access() {
    print!("called rary's `indirect_access()`, that\n> ");

    private_function();
}
$ rustc --crate-type=lib rary.rs
$ ls lib*
library.rlib

Libraries get prefixed with "lib", and by default they get named after their crate file, but this default name can be overridden by passing the --crate-name option to rustc or by using the [crate_name attribute][crate-name].

Summary

Congratulations! You have completed the Creating a Library lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like