6. Building an executable

This chapter describes how to build an executable using rustc.

The examples in this chapter assume the following directory structure:

.
├── executable
│   ├── hw.rs
│   └── use_ops.rs
└── rust_library
    └── libops.rlib

Directory rust_library and its byproducts are described in Building a library.

6.1. Building a simple executable

We are going to build a simple Hello World executable. Source file ./executable/hw.rs contains:

fn main() {
    println!("Hello World!");
}

To create the executable, run:

$ rustc --edition 2021 hw.rs

If you are using CriticalUp, you can use criticalup run in front of the command to invoke the project’s Ferrocene toolchain once installed.

Note

Depending on the compilation target you want to use, you might need to pass additional flags to rustc. Please check the “Required compiler flags” section of your target’s page.

This invocation produces executable hw. Running hw should yield:

Hello World!

6.2. Building a linked executable

We are going to build an executable that depends on library libops we created in the Building a library step. Source file ./executable/use_ops.rs contains:

use ops::addition_ops::add;
use ops::multiplication_ops::mul;

fn main() {
    println!("1 + 2 = {}", add(1, 2));
    println!("3 * 4 = {}", mul(3, 4));
}

The use imports are not necessary as long as uses of the functionality are fully qualified via paths, such as ops::addition_ops::add(1, 2).

To create the executable, run:

$ rustc --edition 2021 -L ../rust_library --extern ops use_ops.rs

If you are using CriticalUp, you can use criticalup run in front of the command to invoke the project’s Ferrocene toolchain once installed.

Note

Depending on the compilation target you want to use, you might need to pass additional flags to rustc. Please check the “Required compiler flags” section of your target’s page.

This invocation produces executable use_ops. Running use_ops should yield:

1 + 2 = 3
3 * 4 = 12

The compiler is capable of linking a binary to different kinds of libraries, such as static, dynamic, and native libraries. To do so, consult the documentation of compiler arguments --extern, -L, and -l.