A static library is an archive of compiled object code that a linker incorporates into an executable. In embedded firmware, a Rust static library lets an existing C application call Rust functions while retaining control of startup, drivers, and the build. section 8.3.2 section 8.6
A minimal Rust library can use no_std, provide a panic handler, and export a function with the C calling convention. The no_mangle attribute gives the function a predictable symbol name; the panic handler below loops indefinitely if a panic occurs. section 8.3.2
#![no_std]
use core::panic::PanicInfo;
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {}
}
#[unsafe(no_mangle)]
pub extern "C" fn square(value: i32) -> i32 {
value.wrapping_mul(value)
}
The library exports square for C and supplies the required panic handler. section 8.3.2
Set crate-type to staticlib in Cargo.toml, then build for the target. For example, cargo build --target thumbv7m-none-eabi --release produces target/thumbv7m-none-eabi/release/libmy_rust_lib.a. Use nm on the archive to check that square appears as an unmangled symbol. section 8.3.2
[package] name = "my_rust_lib" version = "0.1.0" edition = "2024" [lib] crate-type = ["staticlib"] [dependencies]
The Cargo configuration selects the static archive output. section 8.3.2
Declare the exported function in a C header and include it in the C program. An extern "C" guard preserves C linkage when the header is included from C++. The Rust example uses i32 and the C declaration uses int; check type widths when matching an existing C API. section 8.3.2 section 8.3.3
arm-none-eabi-gcc \
-mcpu=cortex-m3 -mthumb \
-ffunction-sections -fdata-sections \
main.c startup.s \
-T stm32f103.ld -nostartfiles \
-L./target/thumbv7m-none-eabi/release \
-lmy_rust_lib \
-Wl,--gc-sections \
-o my_app.elf
This Cortex-M link command combines the C program, startup code, linker script, and Rust archive. section 8.3.3
In the command, -L selects the archive directory and -lmy_rust_lib names libmy_rust_lib.a without its prefix or extension. The linker script and startup code provide the memory layout, vector table, and reset handler; a successful link alone does not guarantee a flashable firmware image. section 8.3.3
A Rust staticlib bundles the local crate and upstream dependencies. Function and data sections, together with linker garbage collection, let the linker discard unreferenced code and limit firmware size. section 8.3.3
For incremental migration, start with a small pure-logic module such as a parser or checksum. The C application can remain in charge while the Rust module is tested on the host before integration into firmware. section 8.6
