Stream: general

Topic: Help with calling printf via FFI (educational compiler proje


view this post on Zulip Elias Little (Jul 21 2025 at 06:57):

I’m writing a simple educational compiler that uses Cranelift to generate code, and I’m trying to call C’s printf function via FFI. Right now, I’m able to print string literals (e.g. "Hello, world!\n"), but I’m having trouble formatting values. For example, when I try printf("Int: %d\n", 42); the format string prints fine, but the %d part either prints garbage/huge random numbers (i.e. 130236440 when expecting 42). I'm compiling statically, but the values also change on every run, so I suspect its maybe a pointer issue?

I’m not super familiar with ABIs or FFI, but I suspect it’s maybe related:

Does this sound like a known limitation or misuse? Is there a Cranelift-supported way to call something like printf("%d\n", 42) safely? I’d be happy to use a C wrapper or another approach if that’s best.

Thanks in advance! And apologies if I’m missing something obvious or if this is the wrong place to ask — still learning and appreciate any help!

view this post on Zulip bjorn3 (Jul 21 2025 at 08:07):

On arm64 macOS variadic arguments are always passed on the stack. This means that you can't just declare printf as having the signature (i64, i32) apple_aarch64. Given that Cranelift doesn't currently natively support calling variadic functions, in cg_clif there is a hack which adds dummy arguments in between the regular arguments and the variadic arguments to force the variadic arguments on the stack: https://github.com/rust-lang/rustc_codegen_cranelift/blob/46fa9ad1f0d0bcc173d44a9a6d721158e2af5ed1/src/abi/mod.rs#L634-L671

Cranelift based backend for rustc. Contribute to rust-lang/rustc_codegen_cranelift development by creating an account on GitHub.

view this post on Zulip Elias Little (Jul 21 2025 at 18:50):

Ah okay thank you! Does simply declaring the signature as (i64, i32) work for x86? And does this work on arm64 macOS for non variadic functions?

view this post on Zulip bjorn3 (Jul 22 2025 at 06:09):

Yes, works on x86 if you don't use float varargs.

view this post on Zulip bjorn3 (Jul 22 2025 at 06:09):

And non-variadic functions work just fine with Cranelift on arm64 macOS.


Last updated: Dec 06 2025 at 05:03 UTC