liveBook · Manning

No_mangle

As explained in Refactoring to Rust

The no_mangle attribute prevents the Rust compiler from applying symbol name mangling to an item.

A C program can declare a Rust function and still fail to link: the linker looks for `solve`, but Rust may give that function a mangled symbol name. `#[no_mangle]` tells the compiler to keep the function’s name available as `solve` instead. section 3.2.2

A function C can call by name

`#[no_mangle] pub extern "C" fn solve(line: *const c_char, solution: *mut c_int) -> c_int { 0 }` combines three distinct requirements: `#[no_mangle]` preserves the symbol name, `pub` makes the function public, and `extern "C"` selects C calling conventions. Compiling a `cdylib` alone does not make every function C-compatible. section 3.2.2

Listing 3.6 Rust solve function that can be exported as compatible with C
#[no_mangle]
pub extern "C" fn solve(
  line: *const c_char, solution: *mut c_int) -> c_int {
  0
}

Compare the attribute, visibility keyword, and calling convention in the complete `solve` signature. section 3.2.2

Mangling normally helps keep symbol names unique. Without it, a named C-facing function needs a name unlikely to clash with other functions. An NGINX handler therefore uses the `ngx_http_calculator` prefix. section 3.2.2 section 4.4

Use the attribute according to how C reaches the function:

  • For a handler C calls by name, use `#[no_mangle]` with `pub` and `extern "C"`. section 4.4
  • For a callback passed to C by its address, use `extern "C"`; its name need not be exposed, so `#[no_mangle]` and `pub` are unnecessary. section 4.4

How Refactoring to Rust covers it

How deep it goes
Explains why mangling obstructs named C linkage and distinguishes it from visibility and calling conventions, without detailing the mangling algorithm.
Examples
Contrasts a calculator’s unresolved `solve` symbol with its annotated Rust function and an NGINX handler with an address-only callback.
What it assumes
Introduces mangling, Rust visibility, and C calling conventions through C integration examples rather than assuming prior knowledge of those Rust annotations.
What you can do after
Operate/configure it on Rust functions C calls by name, while omitting it from callbacks C receives by address.
How it connects
Connects name mangling to dynamic libraries, C FFI, symbol visibility, calling conventions, and callbacks.

Also explained in

Compare how 2 books explain no_mangle →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.