Skip to content

Zig and C

Decades of useful code are written in C: compression, databases, graphics, the operating system itself. Most languages reach that code through a “foreign function interface” with wrappers, binding generators and a separate C compiler. Zig was designed to sit right next to C instead. It can call C functions directly, it can compile C code itself, and it can produce libraries that C programs call. This page covers the basics: calling C, and how C’s types map to Zig’s. The next three pages build on it.

A few things make the difference:

  • Same calling convention. When Zig calls a C function, it passes arguments exactly the way a C compiler would (the “C ABI”). No glue code in between.
  • Zig includes a C compiler. zig cc is a full Clang, and the Zig build system compiles .c files next to your .zig files (Zig as a C Compiler).
  • Zig ships libc for many targets. You can build a C or Zig program that uses libc for Linux, Windows or macOS from any of them, without installing anything else.
  • Zig doesn’t need libc itself. Your Zig programs so far didn’t link the C library at all. Using C is a choice you make, not something you’re stuck with.

The C section of the language reference puts it this way: Zig is independent of C, but acknowledges how important it is to interact with existing C code.

To call a C function, declare it with extern, giving its name and its parameter and return types in Zig terms. Then call it like any other function. Here are three functions from the C standard library:

const std = @import("std");
extern "c" fn puts(s: [*:0]const u8) c_int;
extern "c" fn strlen(s: [*:0]const u8) usize;
extern "c" fn abs(x: c_int) c_int;
pub fn main() void {
_ = puts("Hello from C's puts!");
std.debug.print("strlen says {d}\n", .{strlen("Ziggy")});
std.debug.print("abs(-7) = {d}\n", .{abs(-7)});
}

These functions live in libc, so tell Zig to link it with -lc:

Terminal window
zig run hello_c.zig -lc

You’ll see:

Hello from C's puts!
strlen says 5
abs(-7) = 7

Reading the declarations:

  • extern "c" means “this function exists somewhere outside my Zig code, in the C library, with the C calling convention”. There’s no body, just a signature.
  • c_int is C’s int, and [*:0]const u8 is C’s const char * for text: a pointer to bytes ending in a zero byte. More on both below.
  • puts returns an int we don’t need, so we discard it with _ =, like any unused return value in Zig.

If you forget -lc, Zig tells you right away:

hello_c.zig:3:8: error: dependency on libc must be explicitly specified in the build command
extern "c" fn puts(s: [*:0]const u8) c_int;
^~~

In a build.zig you set .link_libc = true on the module instead; Zig Calling C Libraries shows that.

You don’t have to write every extern yourself. std.c declares a large part of the C library for you (it still needs -lc):

const std = @import("std");
pub fn main() void {
_ = std.c.printf("%d apples and %s\n", @as(c_int, 3), "pears");
}

You’ll see:

3 apples and pears

That @as(c_int, 3) is needed. printf takes a variable number of arguments, and C can’t tell what type a bare Zig literal like 3 should be. Leave it out and Zig says:

main.zig:4:44: error: integer and float literals passed to variadic function must be casted to a fixed-size number type

C’s integer sizes depend on the platform: long is 8 bytes on 64-bit Linux and macOS, but 4 bytes on Windows. So Zig has special types that always match whatever C uses on the target you build for. The reference lists them:

C Zig
char (as a number) c_char
short, unsigned short c_short, c_ushort
int, unsigned int c_int, c_uint
long, unsigned long c_long, c_ulong
long long, unsigned long long c_longlong, c_ulonglong
long double c_longdouble
float, double f32, f64
bool bool
size_t usize
int32_t, uint8_t, … i32, u8, …
void * *anyopaque (or ?*anyopaque if it can be NULL)

This program shows the sizes on the machine it’s built for:

const std = @import("std");
pub fn main() void {
std.debug.print("c_char: {d} byte\n", .{@sizeOf(c_char)});
std.debug.print("c_short: {d} bytes\n", .{@sizeOf(c_short)});
std.debug.print("c_int: {d} bytes\n", .{@sizeOf(c_int)});
std.debug.print("c_long: {d} bytes\n", .{@sizeOf(c_long)});
std.debug.print("c_longlong: {d} bytes\n", .{@sizeOf(c_longlong)});
std.debug.print("usize: {d} bytes\n", .{@sizeOf(usize)});
}

Output:

c_char: 1 byte
c_short: 2 bytes
c_int: 4 bytes
c_long: 8 bytes
c_longlong: 8 bytes
usize: 8 bytes

That’s 64-bit Linux. Built for 64-bit Windows, c_long is 4 bytes. That’s exactly why you write c_long and not i64 when a C function takes a long: the declaration stays right on every platform.

C has one pointer type, T *, that might point at one thing, at an array, or at nothing (NULL). Zig splits that into separate types, so when you write a declaration by hand, you pick the one that says what the C function really does:

The C pointer… Zig type
points to exactly one value *T (or *const T)
points to one value, or is NULL ?*T
points to an array [*]T
is a zero-terminated string (const char *) [*:0]const u8
is a string that might be NULL ?[*:0]const u8

String literals in Zig already end with a zero byte, so you can pass "hello" straight to a [*:0]const u8 parameter. A slice ([]const u8) is different: it has a length but no zero at the end, and C would read past it. Zig refuses:

extern "c" fn puts(s: [*:0]const u8) c_int;
pub fn main() void {
const name: []const u8 = "Ziggy";
_ = puts(name);
}
main.zig:5:14: error: expected type '[*:0]const u8', found '[]const u8'
_ = puts(name);
^~~~

In C, forgetting the terminating zero is a classic bug that reads random memory. Here it’s a compile error. To go between the two worlds:

  • Zig slice to C string: make a copy with a zero at the end, try gpa.dupeSentinel(u8, slice, 0), and free it when C is done with it.
  • C string to Zig slice: std.mem.span(c_string) counts up to the zero and gives you a normal slice.
const std = @import("std");
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
extern "c" fn getenv(name: [*:0]const u8) ?[*:0]const u8;
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
// Zig slice -> C string: copy it with a 0 at the end.
const city: []const u8 = "Lisbon, Portugal"[0..6];
const c_city = try gpa.dupeSentinel(u8, city, 0);
defer gpa.free(c_city);
_ = setenv("CITY", c_city, 1);
// C string -> Zig slice: find the 0 with std.mem.span.
if (getenv("CITY")) |value| {
const s: []const u8 = std.mem.span(value);
std.debug.print("CITY = {s} ({d} bytes)\n", .{ s, s.len });
}
if (getenv("NO_SUCH_VARIABLE") == null) {
std.debug.print("NO_SUCH_VARIABLE is not set\n", .{});
}
}

You’ll see:

CITY = Lisbon (6 bytes)
NO_SUCH_VARIABLE is not set

getenv returns NULL when the variable doesn’t exist, so we declared it as returning an optional pointer, ?[*:0]const u8. Now the compiler makes us check for “no value” with if (...) |value|, which C never did. (For real programs, init.environ_map from Zig Environment Variables is the Zig way to read the environment; getenv is here because it’s a handy C function that returns a string.)

When Zig translates a C header for you (Zig Calling C Libraries shows how), it can’t know whether a double * means one value or an array, or whether it can be NULL. So translated code uses a special C pointer, [*c]T, which allows all of it. The reference says plainly that this type is to be avoided except in generated code. You can pass normal Zig pointers to [*c] parameters, so you’ll see it in translated declarations but rarely type it yourself.

A normal Zig struct doesn’t promise any field order or layout; the compiler may rearrange it. To match a C struct, declare an extern struct, which uses C’s layout rules exactly. C’s div function returns one:

const std = @import("std");
const div_t = extern struct {
quot: c_int,
rem: c_int,
};
extern "c" fn div(numerator: c_int, denominator: c_int) div_t;
pub fn main() void {
const r = div(17, 5);
std.debug.print("17 / 5 = {d} remainder {d}\n", .{ r.quot, r.rem });
}

You’ll see:

17 / 5 = 3 remainder 2

Field order and types must match the C definition. A struct with fields you’re not supposed to touch (like C’s FILE) becomes an opaque {} type instead, and you only ever hold pointers to it (Zig Opaque Types).

Some C functions take a function pointer and call it back. C’s qsort sorts any array, and you give it a function that compares two items. That function will be called by C, so it must use the C calling convention: callconv(.c).

const std = @import("std");
extern "c" fn qsort(
base: *anyopaque,
count: usize,
size: usize,
compare: *const fn (?*const anyopaque, ?*const anyopaque) callconv(.c) c_int,
) void;
fn compareInts(a: ?*const anyopaque, b: ?*const anyopaque) callconv(.c) c_int {
const x: *const c_int = @ptrCast(@alignCast(a.?));
const y: *const c_int = @ptrCast(@alignCast(b.?));
if (x.* < y.*) return -1;
if (x.* > y.*) return 1;
return 0;
}
pub fn main() void {
var numbers = [_]c_int{ 42, 7, 19, 3, 25 };
qsort(&numbers, numbers.len, @sizeOf(c_int), compareInts);
std.debug.print("{any}\n", .{numbers});
}

You’ll see:

{ 3, 7, 19, 25, 42 }

C passes the items as const void *, so compareInts gets ?*const anyopaque and casts each one back to *const c_int with @ptrCast (change the pointer type) and @alignCast (promise it’s aligned for a c_int). This is the kind of untyped code Zig normally saves you from, which is why you’d use std.mem.sort in pure Zig (Zig Sorting). With C, you meet C on its terms.

  • Zig Calling C Libraries: compile your own C files with Zig, link real libraries like zlib, and turn C headers into Zig with the translate-c package.
  • Zig as a C Compiler: zig cc as a drop-in replacement for gcc or clang, including cross-compiling C.
  • Zig Exporting to C: the other direction, writing a library in Zig that C programs call.

Declare C’s int toupper(int c) with extern "c" and use it to print ZIG from the string "zig", one character at a time.

Hint: each character is a u8; pass it as c_int with @intCast (or let it coerce), and turn the result back into a u8 with @intCast. Run with -lc.

Show solution
const std = @import("std");
extern "c" fn toupper(c: c_int) c_int;
pub fn main() void {
for ("zig") |ch| {
const up: u8 = @intCast(toupper(ch));
std.debug.print("{c}", .{up});
}
std.debug.print("\n", .{});
}

You’ll see:

ZIG

A u8 fits in a c_int, so it coerces on the way in. The result is a c_int, so @intCast brings it back to u8 (with a safety check in debug builds).

C declares char *strchr(const char *s, int c);. It returns a pointer to the first c in s, or NULL if there isn’t one. Write the Zig declaration and print what’s left of "hello world" from the first 'w'.

Hint: the result can be NULL and points into a zero-terminated string, so it’s ?[*:0]const u8.

Show solution
const std = @import("std");
extern "c" fn strchr(s: [*:0]const u8, c: c_int) ?[*:0]const u8;
pub fn main() void {
if (strchr("hello world", 'w')) |rest| {
std.debug.print("found: {s}\n", .{std.mem.span(rest)});
} else {
std.debug.print("not found\n", .{});
}
}

You’ll see:

found: world

The optional return type forces you to handle NULL, and std.mem.span turns the C string into a slice for printing.

This doesn’t compile. Fix it.

const std = @import("std");
pub fn main() void {
_ = std.c.printf("%d + %d = %d\n", 2, 3, 2 + 3);
}

Hint: read the error: literals passed to a variadic function need a fixed-size type.

Show solution
const std = @import("std");
pub fn main() void {
_ = std.c.printf("%d + %d = %d\n", @as(c_int, 2), @as(c_int, 3), @as(c_int, 2 + 3));
}

You’ll see (with -lc):

2 + 3 = 5

%d expects a C int, so each literal becomes a c_int.

  • Zig calls C directly using the C ABI; declare a C function with extern "c" fn and call it.
  • Functions from libc need -lc (or .link_libc = true in build.zig); std.c already declares many of them.
  • Use the c_int, c_long, … types so declarations match C on every platform.
  • C strings are [*:0]const u8: string literals fit directly, slices need dupeSentinel(u8, s, 0), and std.mem.span goes back.
  • Pick *T, ?*T, [*]T to say what a C pointer really is; [*c]T is for translated code.
  • extern struct matches C layout, and functions C calls back need callconv(.c).

Next up: Zig Calling C Libraries, compiling C files with your Zig code and translating C headers with the translate-c package.

Quick check

1. You declare extern "c" fn puts(...) and run zig run main.zig. What happens?
2. Which Zig type matches a C const char * that holds text?
3. Why use c_long instead of i64 for a C long parameter?
4. What do you need on a Zig function that C will call through a function pointer?