Quotidien Hebdomadaire Mensuel

Quotidien Shaarli

Tous les liens d'un jour sur une page.

November 17, 2025

Note: Cargo usage by llm

Building from an Existing .rs File

To compile an existing Rust source file (.rs), you can create a new Cargo project around it or use the Rust compiler directly. Here’s how to do both.

Example: Compiling an Existing .rs File With Cargo

Assuming you have an existing Rust file called greeting.rs that looks like this:

// greeting.rs
fn main() {
    println!("Hello from an existing Rust file!");
}

Step 1: Create a New Cargo Project

If you haven't already, create a new Cargo project:

cargo new my_project
cd my_project

Move your existing .rs file into the src directory:

mv path/to/greeting.rs src/

Step 2: Modify Cargo.toml

Open Cargo.toml and set the name to match your project, if necessary.

Step 3: Update main.rs

Replace the contents of main.rs with the following code to include greeting.rs:

// src/main.rs
mod greeting;

fn main() {
    greeting::main();
}

Step 4: Build the Project

Compile the project with:

cargo build

Step 5: Run the Project

After building, you can run your program:

./target/debug/my_project

Output

This should display:

Hello from an existing Rust file!

Compiling Directly with rustc

If you prefer not to use Cargo and just want to compile the existing .rs file directly, you can employ the Rust compiler (rustc).

  1. Navigate to the directory where greeting.rs is located.

  2. Run the following command:

rustc greeting.rs

This compiles greeting.rs and creates an executable called greeting (or greeting.exe on Windows).

  1. To run the executable, use:
./greeting  # Linux or macOS
.\greeting.exe  # Windows

Output

You should see:

Hello from an existing Rust file!

Summary Table of Commands

Command Description
cargo new my_project Creates a new Rust project
mv path/to/greeting.rs src/ Moves an existing .rs file to the project
cargo build Compiles the project
./target/debug/my_project Runs the debug binary
rustc greeting.rs Compiles greeting.rs without Cargo
./greeting Runs the compiled binary

This guide demonstrates how to work with an existing Rust file, using either Cargo or the Rust compiler directly.