Develop with Rust on Ubuntu

This tutorial provides guidance on basic use of the Rust toolchain for development on Ubuntu. It shows how to create a ‘Hello, world!’ program and explains how to compile Rust programs using rustc and build projects using cargo.

For instructions on how to install Rust and related tooling, including IDEs and debuggers, see the dedicated guide on How to set up a development environment for Rust on Ubuntu. This article assumes that tooling suggested in that article has been installed.

cargo vs rustc

rustc is the actual compiler, and cargo is the build system and project management tool.

In most cases, there is no reason to use rustc directly. Instead, use cargo as the build system to call rustc indirectly. Refer to the Rust documentation for an explanation: Why Cargo Exists

If you want to use rustc without cargo, refer to the example Using rustc directly.

Creating a Rust project using Cargo

  1. Create a new Rust project using the new Cargo sub-command:

    cargo new hello_world
    
  2. Change to the project directory:

    cd hello_world
    

    Notice that Cargo has already set up a Git repository with a skeleton project inside (which includes the basic ‘hello world’ program):

    cat src/main.rs
    
    fn main() {
        println!("Hello, world!");
    }
    
  3. Build and run the program:

    dev@ubuntu:~$ cargo run
    Hello, world!

Attention

When building and running the program, if you get an error message related to a missing linker, then you are missing some essential build tools. Install them with:

sudo apt install build-essential

Building programs with nightly Rust

A nightly toolchain can be useful if the new Rust language feature you want to try has yet to land in the stable channel, or if you want to know how the latest Rust compiler optimizes your code.

By default, the nightly Rust builds are not selected for use. Use the +nightly parameter to build your project with the nightly Rust version:

cargo +nightly build

To run the project, use:

cargo +nightly run

Using rustc directly

Consider the following Rust code in a file called answer.rs:

#![no_std]
#[no_mangle]
pub extern "C" fn the_answer() -> usize {
    42
}

Then you have a C program that calls this Rust function in a file called c_main.c:

#include <stdio.h>
#include <unistd.h>

extern size_t the_answer();

int main() {
  printf("The answer is %lu\n", the_answer());
  return 0;
}

Compile the Rust code first:

rustc answer.rs --emit obj --crate-type=lib -Copt-level=3 -o answer.o

Compile and link the final program:

gcc -O3 c_main.c answer.o -o main

When you execute this program, you should see the following:

dev@ubuntu:~$ ./main
The answer is 42