In Rust 2024, why do a 2021 crate's `extern "C"` block and `#[no_mangle]` function stop compiling, and what do the fixes promise?
answer
- someone must vouch for foreign code
- 1.82 syntax, 2024 requirement
- safe and unsafe item qualifiers
- symbol names share one global namespace
basics
~20 sRust 2024 requires unsafe extern blocks and writes no_mangle, export_name and link_section as #[unsafe(...)]. Each unsafe marks a promise rustc cannot check: the declared signatures match the foreign code, and the exported symbol collides with nothing.
solid answer
~50 sOn the 2024 edition rustc rejects a plain `extern "C" { ... }` block with "extern blocks must be unsafe" and a bare `#[no_mangle]` with "unsafe attribute used without unsafe"; `#[export_name]` and `#[link_section]` get the same error. Both spellings, `unsafe extern` and `#[unsafe(...)]`, have been accepted in every edition since Rust 1.82, so a crate can adopt them before it switches. The `unsafe` on the block is the author's claim that every declared signature matches the foreign definition, because a wrong one is undefined behaviour. In return each item can be marked `safe fn` or `safe static`, which callers use without an `unsafe` block, or `unsafe fn`; an unmarked item stays unsafe to call. The unsafe attribute claims the exported symbol name clashes with nothing else in the link. `cargo fix --edition` inserts the keywords but verifies none of these claims.
code
rust · 13 linesextern "C" {
fn abs(x: i32) -> i32;
}
#[no_mangle]
pub extern "C" fn checksum(x: u32) -> u32 {
x.wrapping_mul(31)
}
fn main() {
println!("{}", unsafe { abs(-3) });
println!("{}", checksum(2));
}go deeper
Recall that Rust 2024 wants the unsafe keyword before an extern block and inside the no_mangle, export_name and link_section attributes, and that cargo fix inserts both.
Explain what each unsafe promises: correct foreign signatures for the block, a collision-free symbol for the attribute, and how safe and unsafe item qualifiers decide where callers need unsafe blocks.
Show the review that follows cargo fix: audit each declaration against the C header, mark only precondition-free functions safe, and justify every exported symbol name in a SAFETY comment.
Weigh adopting the 1.82 spelling before the edition switch against the library's oldest supported toolchain, and decide who on the team may approve a foreign item declared safe.
## What the 2024 edition rejects A crate that talks to C usually has two kinds of FFI code: an `extern` block that **declares** functions defined in a C library, and Rust functions **exported** under a fixed symbol name so C can call them. Code like this compiled on every edition up to 2021: ```rust extern "C" { fn abs(x: i32) -> i32; } #[no_mangle] pub extern "C" fn checksum(x: u32) -> u32 { x.wrapping_mul(31) } ``` Switch the crate to `edition = "2024"` and rustc 1.99 stops with two errors, neither carrying an E-code: - `error: extern blocks must be unsafe`, with the help text "needs `unsafe` before the extern keyword"; - `error: unsafe attribute used without unsafe`, with the help "wrap the attribute in `unsafe(...)`". The second rule covers exactly three attributes: `no_mangle`, `export_name` and `link_section`. Other attributes are untouched; `#[unsafe(inline)]` is rejected because "`inline` is not an unsafe attribute". The `pub extern "C" fn checksum` definition itself needs no `unsafe`: it is an ordinary safe Rust function with a C calling convention, and Rust code calls it without an `unsafe` block. ## Unsafe extern blocks: who vouches for a signature rustc cannot read the C library, so it trusts whatever the `extern` block says about argument and return types. If the declaration says `i32` and the C function takes a pointer, every call is **undefined behaviour**. Before 2024 that trust was implicit; the 2024 edition makes the block's author write `unsafe extern "C" { ... }` so the claim is visible and reviewable. The mistakes the claim covers are the ones rustc cannot see: - an integer of the wrong width, such as `i64` for a C `long`, which is 32 bits on 64-bit Windows (`core::ffi::c_long` follows the target); - a value where the C function takes a pointer, or the reverse; - a missing or extra argument, or the wrong return type. The syntax arrived in **Rust 1.82** for every edition and became mandatory with the 2024 edition (stable since 1.85). The new block form also lets the author grade each item: | Item written as | Call or use needs an `unsafe` block? | |---|---| | `pub safe fn abs(x: i32) -> i32;` | No: the author asserts it has no preconditions | | `pub unsafe fn strlen(s: *const c_char) -> usize;` | Yes | | `pub fn labs(x: i64) -> i64;` (no qualifier) | Yes; unqualified items default to unsafe, and a call without a block fails with E0133 | | `pub safe static TABLE: [u8; 256];` | No | A `safe` qualifier is legal only inside an `unsafe extern` block. In a plain `extern` block rustc reports "items in `extern` blocks without an `unsafe` qualifier cannot have safety qualifiers". ## Unsafe attributes: symbol names are global Every library linked into a program shares one symbol namespace. Name mangling normally keeps Rust symbols unique, and these three attributes switch it off or redirect it. The edition guide's example is `#[export_name = "malloc"]` on a safe function, which crashes most Unix-like programs at start-up despite containing no `unsafe` code. Writing `#[unsafe(export_name = "...")]` or `#[unsafe(no_mangle)]` records that the author has checked no other definition of that symbol exists; the convention is a `// SAFETY:` comment saying why. `link_section` is covered for the same reason: choosing the object-file section an item lands in is another linking decision rustc cannot check. ## Migrating a crate 1. Run `cargo fix --edition`. Its lints `missing_unsafe_on_extern` and `unsafe_attr_outside_unsafe` (both in the `rust-2024-compatibility` group) prefix each block with `unsafe` and wrap each attribute. 2. Review every declaration against the C header. The fix adds a keyword; it does not check a single type. 3. Decide which foreign functions really have no preconditions and mark only those `safe`. The fix never adds `safe`, so after migration every call still sits in an `unsafe` block. 4. Write `// SAFETY:` comments on the unsafe attributes explaining why the symbol name is unique. Because both spellings work from 1.82 on, a library can make these edits while still on 2021, as long as it no longer supports toolchains older than 1.82. ## Neighbouring 2024 changes The same edition turns the `unsafe_op_in_unsafe_fn` lint into a warning and makes references to a `static mut` a deny-by-default lint. Those belong with the material on unsafe Rust; here they matter only as further lines in the migration diff to review.
- Does an `extern "C" fn` that Rust defines for C to call also need `unsafe` in Rust 2024?No. The 2024 rule covers `extern` blocks, which declare foreign items, and the three symbol attributes. A Rust-defined `pub extern "C" fn checksum(x: u32) -> u32` is an ordinary safe function with the C calling convention, so Rust code calls it without an `unsafe` block. Only its `#[no_mangle]` has to become `#[unsafe(no_mangle)]`.
- Can a 2021-edition crate already write `unsafe extern` with `safe fn` items?Yes, on Rust 1.82 or later: the block qualifier and the item qualifiers are accepted in every edition from that release, so a library can change spelling first and switch editions later. What 2021 rejects is a `safe` qualifier inside a plain `extern` block; rustc says items in `extern` blocks without an `unsafe` qualifier cannot have safety qualifiers.
- What does `cargo fix --edition` change in an `extern` block, and what is left for you?Its migration lint prefixes the block with `unsafe` and leaves every item unqualified, so all calls still need `unsafe` blocks. It cannot check a signature against the C header, and it never marks an item `safe`. Auditing the declarations, choosing which functions truly have no preconditions, and writing `// SAFETY:` comments for the unsafe attributes are manual work.
- Writing unsafe extern makes every foreign function safe to call
- The 2024 edition changed the C calling convention of extern functions
- cargo fix --edition checks extern declarations against the C header
- unsafe extern needs the 2024 edition, so 2021 crates cannot write it
- The compiler verifies that an item declared safe fn really is safe
Assumes Rust 1.99 on the 2024 edition (stable since 1.85); unsafe extern and #[unsafe(...)] are accepted in every edition since 1.82 and required from 2024.