Sub topic 2
Declaring and calling C functions
This chapter shows how to tell the Rust compiler about a C function and how to call it. It assumes you know basic Rust (ownership, borrowing, Result), can run a Cargo project, understand C pointers, and know that unsafe marks code the compiler cannot check. The previous chapter covered why the C ABI is the common ground between the two languages. This chapter covers the mechanics.
The working model
Rust cannot read C source or C headers. To call a C function, you write a declaration in Rust that states the function's name and its signature. The compiler trusts that declaration completely. It emits a call using the C calling convention, and it leaves a reference to the symbol name for the linker to resolve.
Nothing in this chain checks that your declaration matches the real C function. A wrong type, a missing argument, or a misspelled name is not a compile error. You get a link error at best, and silent undefined behavior at worst.
A first call
The smallest working example uses two functions from the C standard library. Rust programs already link against it on common platforms, so no extra setup is needed.
use std::ffi::{c_char, c_int, CString};
unsafe extern "C" {
fn abs(input: c_int) -> c_int;
fn strlen(s: *const c_char) -> usize;
}
fn main() {
let n = unsafe { abs(-3) };
let s = CString::new("hello").unwrap();
let len = unsafe { strlen(s.as_ptr()) };
println!("{n} {len}");
}This prints 3 5. Three parts matter.
unsafe extern "C" { ... }is an extern block. It contains declarations only, with no function bodies. The string"C"names the ABI, meaning the calling convention and data layout rules the functions follow.extern { ... }with no string also means"C", but writing it out is clearer.- Each declaration ends with a semicolon. It reads like a Rust function signature, but it describes a function that lives somewhere else.
- Each call sits in an
unsafeblock. By default, every function declared in an extern block is unsafe to call, because the compiler cannot verify anything about it.
The `unsafe extern` keyword and editions
Since Rust 1.82, you can write unsafe extern "C". In the 2024 edition it is required, and a plain extern "C" block is an error. In older editions both forms compile. Use unsafe extern in new code, because the unsafe on the block states that you are vouching for the declarations inside it.
Marking declarations `safe`
In an unsafe extern block you can mark an individual function safe. Callers then do not need an unsafe block.
use std::ffi::c_int;
unsafe extern "C" {
pub safe fn abs(input: c_int) -> c_int;
}
fn main() {
println!("{}", abs(-7));
}This compiles and prints 7, but it is a trap. In C, abs(INT_MIN) is undefined behavior, because the result does not fit in an int. Marking abs as safe makes every caller in your crate able to trigger undefined behavior without writing unsafe. Use safe fn only when no argument value can cause undefined behavior and the function has no other preconditions. Otherwise write a wrapper that enforces the preconditions:
use std::ffi::c_int;
unsafe extern "C" {
fn abs(input: c_int) -> c_int;
}
pub fn checked_abs(x: c_int) -> Option<c_int> {
if x == c_int::MIN {
None
} else {
Some(unsafe { abs(x) })
}
}
fn main() {
println!("{:?} {:?}", checked_abs(-3), checked_abs(c_int::MIN));
}This prints Some(3) None. The unsafe block is small, and the reason it is sound is visible right next to it. Chapter nine returns to this pattern.
What the compiler does and does not check
The compiler checks that your Rust call matches your Rust declaration. It does not check that the declaration matches C. That gap is where FFI bugs come from.
| Mistake | What happens |
|---|---|
| Misspelled function name | Link error: undefined symbol. Safe failure. |
| Library not linked | Same link error. Safe failure. |
| Wrong argument or return type | Compiles and links. Undefined behavior at run time. |
| Wrong argument count | Compiles and links. Undefined behavior at run time. |
| Passing a dangling or null pointer | Compiles. Crash or memory corruption. |
Rust does warn when the same C function is declared twice with different signatures in one crate. The clashing_extern_declarations lint reports this. It only compares declarations inside your own crate. It cannot compare them to the C source.
Reading a C prototype
Translate a prototype one piece at a time. Take this C declaration:
size_t strlen(const char *s);size_tmaps tousizeon mainstream platforms.const char *maps to*const c_char.- The function name stays exactly the same.
A C function returning void becomes a Rust function with no return type, which is (). A C function with no parameters is declared with empty parentheses in Rust.
The next chapter goes through type mapping in detail. For now, three rules are enough.
- Use the aliases from
std::ffi, such asc_int,c_char,c_long, andc_double, instead ofi32ori8. The aliases track the platform's real sizes. - Write pointers as raw pointers,
*const Tor*mut T. Matchconstin C with*constin Rust. - Do not use Rust-only types such as
String,Vec<T>,&str, orOption<String>in a declaration. C does not know their layout.
You can use references (&T, &mut T) in declarations, but they promise Rust's aliasing and validity rules. A C function that might receive null should take a raw pointer. The third example in this tutorial uses references to pass valid structs, which is a deliberate choice you must justify each time.
Why the declaration must match exactly
Consider this wrong declaration of strlen:
use std::ffi::{c_char, c_int};
unsafe extern "C" {
fn strlen(s: *const c_char) -> c_int; // wrong: C returns size_t
}On a 64-bit Linux machine, size_t is 64 bits and c_int is 32 bits. The caller reads only part of the return register. For short strings the result may look correct, and the program may pass its tests. The code is still wrong. A different platform or compiler could break it, and the compiler is allowed to assume the declaration is true when it optimizes.
The same applies to argument counts and types. The C ABI passes arguments in registers and on the stack according to fixed rules. If you pass a f32 where C expects a double, the callee reads garbage. Nothing warns you.
Choosing the symbol name
Rust normally mangles function names so that generics and modules do not collide. Functions in an extern block are never mangled. The identifier you write is the symbol the linker looks for.
If the Rust name should differ from the C name, use #[link_name]:
use std::ffi::{c_char, c_int, CString};
unsafe extern "C" {
#[link_name = "strlen"]
fn c_strlen(s: *const c_char) -> usize;
#[link_name = "abs"]
fn c_abs(input: c_int) -> c_int;
}
fn main() {
let s = CString::new("rust").unwrap();
println!("{} {}", unsafe { c_strlen(s.as_ptr()) }, unsafe { c_abs(-1) });
}This prints 4 1. Renaming helps when a C name clashes with something in your module, or when you want a prefix to mark raw bindings.
Variadic functions
C functions such as printf take a variable number of arguments. Rust lets you declare them with ... as the last parameter:
use std::ffi::{c_char, c_int};
unsafe extern "C" {
fn printf(format: *const c_char, ...) -> c_int;
}You can call a variadic C function from Rust, but you cannot define one in stable Rust. Extra arguments are passed without any type checking, and the format string decides how C interprets them. A mismatch between the format string and the arguments is undefined behavior. Also, C's stdout buffer is separate from Rust's, so output from printf and println! can appear out of order when the output is piped. Where possible, prefer a non-variadic variant such as vsnprintf, or do the formatting in Rust and pass the finished string.
What you must guarantee at each call
An unsafe block around a C call means you have checked these things yourself:
- Signature. The declaration matches the C prototype in types, count, and return type.
- Pointers. Every pointer is valid for the access the function makes. It is non-null unless C accepts null, and it is aligned and not dangling.
- Strings. Every
char *that C reads as a string ends with a zero byte and contains no interior zero bytes. - Lifetimes. C does not keep a pointer past the call unless you have arranged for the data to live long enough.
- Threads. The function is safe to call from the thread you are on. Many C libraries are not thread-safe.
- Preconditions. Any documented rule, such as "argument must not be
INT_MIN", holds.
Common errors
Undefined symbol at link time. The message looks like undefined reference to 'foo' on Linux or unresolved external symbol foo with MSVC. Check the spelling, then check that the library is linked. Linking is covered in a later chapter.
Missing unsafe. Calling an extern function outside an unsafe block gives error E0133. Wrap the call in unsafe, or write a wrapper function that does so after checking preconditions.
Plain extern block in the 2024 edition. The compiler asks for unsafe extern. Add the keyword.
Name clash. If two Rust modules declare the same C function with different types, the lint above fires. Declare each C function once in a single module and re-export it.
Assuming the C standard library is always available. It is linked by default on common desktop and server targets. On embedded or no_std targets, you may need to link it yourself.
Exercises
Exercise
A teammate declares fn strlen(s: *const c_char) -> c_int; and it prints correct results in tests on a 64-bit Linux machine. Why is the declaration still wrong, and what should it be?
Show answer
The C prototype returns size_t, which is 64 bits wide on that platform, while c_int is 32 bits. The compiler trusts the declaration, so the caller reads the wrong width of the return value. Short strings can hide the problem, but the behavior is undefined and may break on other targets or builds. The correct declaration is fn strlen(s: *const c_char) -> usize;.
Exercise
You declare pub safe fn abs(input: c_int) -> c_int; in an unsafe extern "C" block. Name the input that makes this unsound, and show how to fix it without using safe fn.
Show answer
c_int::MIN makes it unsound, because abs(INT_MIN) is undefined behavior in C. Declare abs as a normal (unsafe) extern function and write a wrapper such as pub fn checked_abs(x: c_int) -> Option<c_int> that returns None when x == c_int::MIN and otherwise returns Some(unsafe { abs(x) }).