How do I make a Rust program which can be executed without using `cargo run`?

Viewed 9024

How can I make a program in Rust which can be executed from anywhere without using cargo run, by just clicking on the file?

Is there any crate? I have written code for snake game and I want to run it by just clicking on a file.

4 Answers

If you compile a Rust application with:

cargo build --release

it will place a binary file in ./target/release. So if your application is called snake_game, you can run it with ./target/release/snake_game, or by double-clicking on that file.

This binary is completely self-contained, so you can move or copy it to somewhere else on your computer.

First build your binary for release

cargo build --release 

Next handle permissions

Typically chmod +x target/release/whateverYourProgramIsCalled to make executable, but cargo did this for us already

You can check it's Octal Permissions

ls -l target/release/whateverYourProgramIsCalled
chmod +x target/release/whateverYourProgramIsCalled
ls -l target/release/whateverYourProgramIsCalled

As you can see nothing has changed... the permissions were already correct for executing

Run that executable

./whateverYourProgramIsCalled 

Optional: run from anywhere

You can run that binary anywhere from the command line

To do this you need to add it to your path

For mac you can add to your path from /etc/paths

whatever editor you prefer.... vi, code, etc...

sudo code /etc/paths

I added a path like this, saved and authenticated with a password

/Users/`whoami`/code/rust/binaries

whoami command is surrounded by `

next copy your new binary over to where it needs to be, in that binaries folder

cp whateverYourProgramIsCalled /Users/`whoami`/code/rust/binaries

Then open a new terminal window

Check your command is in your path

where whateverYourProgramIsCalled

Run your command from anywhere

whateverYourProgramIsCalled 

Rejoice

There is another method you can do by using rustc. It will create an executable binary file in the same directory where your file exists.

Make sure you are in the src directory and the name of your file is main.rs.

rustc main.rs
./main

The advantage of using rustc is that you can run any file not only main.rs. just do:

 rustc filename.rs
 ./filename

You can run it from terminal and also by clicking on that file.

Just wanted to add another answer here, not sure if it's related to a more recent version of rust.

If in the root of your project you just run the command cargo install --path . it will add it to cargo and allow you to run the binary just with project name.

Related