【Rust】使用庫文件


環境

  • Rust 1.56.1
  • VSCode 1.61.2

概念

參考:https://doc.rust-lang.org/stable/rust-by-example/crates/using_lib.html

示例

要鏈接到指定的庫,可以通過 --extern 參數來指定。

rustc 鏈接庫

fn main() {
    rary::public_function();
    // 編譯錯誤,私有方法
    //rary::private_function();
    rary::indirect_access();
}
PS C:\Users\\work\workspace\rust\rust\src> rustc main.rs --extern rary=library.rlib
PS C:\Users\\work\workspace\rust\rust\src> .\main.exe
called rary's `public_function()`
called rary's `indirect_access()`, that
> called rary's `private_function()`

cargo

建立如下的文件結構:

│  Cargo.toml
├─rary
│  │  Cargo.toml
│  └─src
│          lib.rs
└─src
        main.rs

lib.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();
}

main.rs 中的內容:

fn main() {
    rary::public_function();
    rary::indirect_access();
}

cargo.toml

[dependencies]
rary={path="rary"}

總結

了解了 Rust 中使用庫文件的方式,通過 rustc 可以直接鏈接到庫文件,而 cargo 可以將兩個項目鏈接到一起。

附錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM