温馨提示×

怎样在Debian用Rust编译

小樊
48
2026-09-29 07:48:32
栏目: 编程语言

在 Debian 上用 Rust 编译程序,通常分为 安装 Rust 工具链 → 编写代码 → 编译运行 几个步骤。下面给你一个清晰、常用的流程。


一、安装 Rust(推荐方式)

1️⃣ 使用官方 rustup(最推荐)

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

安装完成后,按提示执行:

source "$HOME/.cargo/env"

验证是否成功:

rustc --version
cargo --version

2️⃣ (不推荐但可用)Debian 仓库安装

sudo apt update
sudo apt install rustc cargo

⚠️ 版本通常较旧,不建议用于新项目。


二、创建 Rust 项目

cargo new hello
cd hello

目录结构:

hello
├── Cargo.toml
└── src
    └── main.rs

三、编写代码(示例)

src/main.rs:

fn main() {
    println!("Hello, Debian!");
}

四、编译与运行

1️⃣ 开发模式(快,带调试)

cargo run

2️⃣ 仅编译

cargo build

生成文件:

target/debug/hello

运行:

./target/debug/hello

3️⃣ 发布模式(优化,慢但快运行)

cargo build --release
./target/release/hello

五、可能需要安装的依赖

如果编译失败,可能需要:

sudo apt install build-essential

部分项目(如 OpenSSL)还需要:

sudo apt install pkg-config libssl-dev

六、常见问题

❓ 找不到 rustc

source "$HOME/.cargo/env"

或写入 .bashrc / .zshrc:

export PATH="$HOME/.cargo/bin:$PATH"

❓ 交叉编译?

可以,但需额外 target:

rustup target add x86_64-unknown-linux-musl

如果你愿意,可以告诉我:

  • 是 命令行程序 / Web 服务 / 系统程序?
  • 是否要 静态编译 / 交叉编译 / 容器里跑?

我可以给你更针对性的方案。

0 踩