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.

The Rust attribute #[no_mangle] prevents the compiler from mangling an item’s symbol name. It is useful when C code must find a Rust function by name: otherwise, the linker may look for solve while Rust has given the function a name such as _ZN9calculate5solve17h6ed798464632de3fE. 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
}

This function combines #[no_mangle] with pub and extern "C" so C can call solve by name. The attribute controls the symbol name; pub exposes the function, and extern "C" selects C calling conventions. section 3.2.2

Disabling mangling means the name must not clash with another symbol. A C-style prefix, such as ngx_http_calculator_, helps distinguish an exported function from others. section 3.2.2 section 4.4

#[no_mangle]
pub unsafe extern "C" fn ngx_http_calculator_handler

unsafe extern "C" fn read_body_handler

unsafe fn request_body_as_str

Not every function callable from C needs #[no_mangle]. The handler is called by name, but the callback is passed by address, so it needs extern "C" without a public, unmangled name. The Rust-only helper needs neither annotation. section 4.4

How Refactoring to Rust covers it

How deep it goes
Explains symbol naming and export annotations through function signatures, while leaving the mangling algorithm unexplored.
Examples
Contrasts a C-callable calculator function with an NGINX request handler and an address-passed callback.
What you can do after
Apply it to expose a Rust function by name to C while choosing appropriate visibility, calling conventions, and a collision-resistant name.
How it connects
Connects name mangling with C FFI, linking, calling conventions, callbacks, and symbol collisions.

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.