FAQ - Help and questions

What replaces C preprocessor macros (#define) in Rust?

#porting#c-language#macrospublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A constant #define becomes const, a function-like macro becomes a normal or generic function (const fn if needed at compile time), and conditional compilation becomes cfg. Only macros that repeat code or take variable arguments need macro_rules!. Functions evaluate arguments once, removing a classic C bug.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

CRust
#define BUFSIZE 4096const 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 constantsconst 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 listsconst items, or a flags!-style macro for long lists
#ifdef _WIN32#[cfg(windows)] or cfg!(windows)
#includeuse 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.

src/main.rsrust
// 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);
}
text
2
calls = 2
4096 144 2.5
5
3
[log] 3 items, flags 2

max_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#

  1. Go through every #define in the headers you port, and sort it into the table's rows.
  2. Constants first: replace with const (or static when it needs an address). Give each one a type.
  3. Function-like macros next: write a function. If it must work for several types, make it generic with a trait bound (PartialOrd above). Add #[inline] only if you measured a need; the compiler already inlines small functions.
  4. 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).
  5. Port #ifdef blocks 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 #define constants as static mut. Use const.
  • 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet