Answer#
Most C macros exist because C has no better tool: no compile-time constants of every type, no generics, no inline functions in old code. Rust has all of them, so most macros become ordinary code that the compiler type-checks.
| C | Rust |
|---|---|
#define BUFSIZE 4096 | const BUFSIZE: usize = 4096; |
#define MAX(a, b) ((a) > (b) ? (a) : (b)) | a generic function fn max_of<T: PartialOrd>(a: T, b: T) -> T |
#define SQUARE(x) ((x) * (x)) used in constants | const fn square(x: u32) -> u32 |
#define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0])) | a.len() (slices and arrays know their length) |
#define LOG(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__) | a macro_rules! macro, or a call to eprintln! |
#define FLAG_READ (1 << 0) and similar lists | const items, or a flags!-style macro for long lists |
#ifdef _WIN32 | #[cfg(windows)] or cfg!(windows) |
#include | use and mod |
The program ports a set of typical macros. It was compiled and run with rustc 1.93.0. The first two lines show the classic macro bug in the other direction: the generic max_of evaluates each argument exactly once, so a call with side effects behaves the way it reads.
// C: #define BUFSIZE 4096
const BUFSIZE: usize = 4096;
// C: #define MAX(a, b) ((a) > (b) ? (a) : (b)) (evaluates an argument twice)
fn max_of<T: PartialOrd>(a: T, b: T) -> T {
if a > b { a } else { b }
}
// C: #define SQUARE(x) ((x) * (x)) usable in constants
const fn square(x: u32) -> u32 {
x * x
}
const AREA: u32 = square(12);
// C: #define LOG(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__) -> a macro, because the arguments are variable
macro_rules! log {
($($arg:tt)*) => { eprintln!("[log] {}", format!($($arg)*)) };
}
// repeated code: one macro line per name
macro_rules! flags {
($($name:ident = $bit:expr),* $(,)?) => { $(const $name: u32 = 1 << $bit;)* };
}
flags!(READ = 0, WRITE = 1, EXEC = 2);
fn main() {
let mut calls = 0;
let mut next = || { calls += 1; calls };
println!("{}", max_of(next(), next()));
println!("calls = {calls}");
println!("{BUFSIZE} {AREA} {}", max_of(2.5, 1.5));
println!("{}", READ | EXEC);
let items = [10, 20, 30];
println!("{}", items.len());
log!("{} items, flags {}", items.len(), WRITE);
}2
calls = 2
4096 144 2.5
5
3
[log] 3 items, flags 2max_of(next(), next()) calls next twice and gets 1 and 2, so the result is 2 and calls is 2. The C macro MAX(next(), next()) would expand to a comparison that calls the function three times, because the winning argument is evaluated a second time (this is how the C preprocessor works; C was not run here). The last output line is written to standard error by eprintln!.
How to do it#
- Go through every
#definein the headers you port, and sort it into the table's rows. - Constants first: replace with
const(orstaticwhen it needs an address). Give each one a type. - Function-like macros next: write a function. If it must work for several types, make it generic with a trait bound (
PartialOrdabove). Add#[inline]only if you measured a need; the compiler already inlines small functions. - Keep
macro_rules!for what functions cannot do: a variable number of arguments, repeating a pattern for a list of names, or generating items (functions, constants, types). - Port
#ifdefblocks to#[cfg(...)]attributes on the items they guard, so that the compiler still checks the syntax of the disabled branch where possible.
Common mistakes#
- Porting
#defineconstants asstatic mut. Useconst. - Writing a
macro_rules!for something a generic function can do. Functions give better error messages and work with tools. - Forgetting that a Rust macro is expanded before type checking: an error inside the expansion points at the macro call, which can be confusing. Keep macros small.
Related questions#
Is there an equivalent of assert and __LINE__?#
Yes: assert!, debug_assert!, line!(), file!() and module_path!() are in the standard library.
What about include guards and header files?#
Not needed. Modules and use replace them, and the compiler reads each item once.
Sources#
- The Rust Book, "Macros": https://doc.rust-lang.org/book/ch20-05-macros.html
- The Rust Reference, "Macros By Example": https://doc.rust-lang.org/reference/macros-by-example.html
- The Rust Reference, "Conditional compilation": https://doc.rust-lang.org/reference/conditional-compilation.html