14. C Interoperability {#14-c-interoperability}

July 5, 2026 ยท View on GitHub

+++ title = "14. C Interoperability" weight = 14 +++

14. C Interoperability {#14-c-interoperability}

Zen C offers two ways to interact with C code: Trusted Imports (Convenient) and Explicit FFI (Safe/Precise).

Method 1: Trusted Imports (Convenient)

You can import a C header directly using the import keyword with the .h extension. This treats the header as a module and assumes all symbols accessed through it exist.

//> link: -lm
import "math.h" as c_math;

fn main() {
    // Compiler trusts correctness; emits 'cos(...)' directly
    let x = c_math::cos(3.14159);
}

Pros: Zero boilerplate. Access everything in the header immediately. Cons: No type safety from Zen C (errors caught by C compiler later).

Method 2: Explicit FFI (Safe)

For strict type checking or when you don't want to include the text of a header, use extern fn.

include <stdio.h> // Emits #include <stdio.h> in generated C

// Define strict signature
extern fn printf(fmt: char*, ...) -> c_int;

fn main() {
    printf("Hello FFI: %d\n", 42); // Type checked by Zen C
}

Pros: Zen C ensures types match. Cons: Requires manual declaration of functions.

import vs include

  • import "file.h": Registers the header as a named module. Enables implicit access to symbols (for example, file::function()).
  • include <file.h>: Purely emits #include <file.h> in the generated C code. Does not introduce any symbols to the Zen C compiler; you must use extern fn to access them.

Standard Library

Zen C includes a standard library (std) covering essential functionality.

Browse the Standard Library Documentation

Key Modules

Click to see all Standard Library modules
ModuleDescriptionDocs
std/bigfloat.zcArbitrary-precision floating-point arithmetic.Docs
std/bigint.zcArbitrary-precision integer BigInt.Docs
std/bits.zcLow-level bitwise operations (rotl, rotr).Docs
std/complex.zcComplex Number Arithmetic Complex.Docs
std/vec.zcGrowable dynamic array Vec<T>.Docs
std/string.zcHeap-allocated String type with UTF-8 support.Docs
std/queue.zcFIFO queue (Ring Buffer).Docs
std/map.zcGeneric Hash Map Map<V>.Docs
std/fs.zcFile system operations.Docs
std/io.zcStandard Input/Output (print/println).Docs
std/option.zcOptional values (Some/None).Docs
std/result.zcError handling (Ok/Err).Docs
std/path.zcCross-platform path manipulation.Docs
std/env.zcProcess environment variables.Docs
std/net/TCP, UDP, HTTP, DNS, URL.Docs
std/thread.zcThreads and Synchronization.Docs
std/time.zcTime measurement and sleep.Docs
std/json.zcJSON parsing and serialization.Docs
std/stack.zcLIFO Stack Stack<T>.Docs
std/set.zcGeneric Hash Set Set<T>.Docs
std/process.zcProcess execution and management.Docs
std/regex.zcRegular Expressions (TRE based).Docs
std/simd.zcNative SIMD vector types.Docs