global_asm! emits a module-level block of assembler text that becomes standalone functions or data symbols in the linked object or executable. Use it when assembly must exist outside one Rust function, such as startup code, custom interrupt handlers, secure gateways, or trap handlers. section 5.5.4
A global_asm! block can:
- Declare labels and globally visible symbols with directives such as .global. section 5.5.4
- Choose a section and define arbitrary control flow without inline operand bindings. section 5.5.4
- Expose a routine to Rust through an unsafe extern "C" declaration. section 5.5.4
An out-of-line delay loop
The pattern is to define a globally visible assembly symbol, implement its loop, and declare that symbol for Rust callers. The routine must follow the target ABI: preserve callee-saved registers, maintain stack invariants, and return with the architecture-correct instruction. On Cortex-M, exception entry already saves r0–r3, r12, LR, PC, and xPSR; additional registers still require care. section 5.5.4 section 5.6
use core::arch::global_asm;
// global_asm!() out-of-line counted delay loop
global_asm!(r#"
.global asm_delay_loop
.thumb_func
asm_delay_loop:
cbz r0, 2f
1:
subs r0, r0, #1
bne 1b
2:
bx lr
"#);
Use the listing to see a complete global_asm! delay-loop definition with a global symbol, Thumb directive, labels, branching, and return. section 5.5.4
// Declare the symbol so Rust code can reference it.
unsafe extern "C" {
fn asm_delay_loop(iterations: u32);
}
Use the companion declaration to see how Rust names the assembly symbol through an unsafe extern "C" function. section 5.5.4
Prefer Rust intrinsics when they provide the required operation. Choose asm! for instruction sequences with precise operands, and choose global_asm! or an external .S file when a complete module-level routine is clearer. section 5.6
