温馨提示×

Linux下Rust编译器如何使用

小樊
45
2025-12-10 09:21:47
栏目: 编程语言

Linux 下 Rust 编译器使用指南

一 安装与验证

  • 推荐安装方式:使用 rustup 管理工具链(包含 rustccargo)。在终端执行:
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
    source "$HOME/.cargo/env"
    
    安装完成后验证:
    rustc -Vv
    cargo -V
    
    如需系统级包管理器安装(版本通常较旧),在 Debian/Ubuntu 可执行:
    sudo apt update && sudo apt install rustc
    
    但开发与日常使用更建议 rustup,便于多版本与组件管理。

二 使用 Cargo 创建与构建项目

  • 创建项目:
    cargo new hello_world
    cd hello_world
    
  • 常用构建与运行:
    cargo build        # 调试构建,产物在 target/debug/
    cargo run         # 编译并运行
    cargo build --release  # 发布构建,产物在 target/release/(更高优化)
    
  • 直接单文件编译(不使用 Cargo):
    rustc main.rs
    ./main
    
    上述命令覆盖日常开发中最常用的构建、运行与发布流程。

三 常用构建与链接参数

  • 指定输出类型(库或可执行):
    rustc --crate-type bin main.rs     # 可执行
    rustc --crate-type rlib lib.rs     # Rust 静态库 .rlib
    rustc --crate-type dylib lib.rs     # Rust 动态库 .so
    rustc --crate-type staticlib lib.rs # 原生静态库 .a
    rustc --crate-type cdylib lib.rs   # 原生动态库 .so(供 C 调用)
    
  • 指定 crate 名称与输出文件:
    rustc --crate-name myapp main.rs
    rustc main.rs -o app
    
  • 库搜索路径与链接原生库:
    rustc main.rs -L dependency=/path/to/deps -l dylib=ssl
    
  • 条件编译与代码生成输出:
    rustc --cfg feature="foo" main.rs
    rustc --emit asm,llvm-ir,obj main.rs
    rustc --emit asm=out.s,llvm-ir=out.ir main.rs
    
    以上参数适用于需要自定义产物类型、链接第三方库、条件编译或导出中间产物的场景。

四 工具链管理与国内镜像

  • 更新工具链与组件:
    rustup update
    rustup component add rustfmt clippy
    
  • 设置默认工具链(稳定版/测试版/夜间版):
    rustup default stable
    rustup default nightly
    
  • 中国大陆常用镜像(加速工具链与 crate 索引):
    • 安装阶段镜像环境变量:
      export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup
      export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup
      curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
      
    • crate 索引镜像(写入 Cargo 配置):
      mkdir -p ~/.cargo
      cat > ~/.cargo/config.toml <<EOF
      [registries]
        crates-io = { index = "https://mirrors.tuna.tsinghua.edu.cn/crates.io-index" }
      EOF
      
    以上可显著提升在国内的安装与依赖下载速度。

五 调试与编辑器配置

  • 使用 VS Code 进行开发与调试:
    • 安装扩展:rust-analyzer(语言支持与智能提示)与 CodeLLDB(或 Native Debug,调试器)。
    • 调试流程:在调试视图创建调试配置(launch.json),选择 LLDB 作为调试器,设置程序入口(如 target/debug/your_bin),即可断点调试。
    • 提示:rust-analyzer 提供代码补全、跳转、重构等体验;断点调试依赖调试器后端(CodeLLDB/Native Debug)。

0