Zig Calling C Libraries
Zig and C showed how to call a C function from libc by writing its extern declaration yourself. Real projects go further: you have your own C files to compile, a C library installed on the system, and headers with dozens of functions you don’t want to declare by hand. This page walks through all three, using the Zig 0.17 way of doing things. One heads-up first: in 0.17, @cImport is gone, so a lot of older tutorials won’t compile any more. You’ll see what replaced it.
Compile a C file together with Zig
Section titled “Compile a C file together with Zig”Say you have a tiny C library, a header and a source file:
#ifndef MATHLIB_H#define MATHLIB_H
int add(int a, int b);double average(const double *values, int count);
#endif#include "mathlib.h"
int add(int a, int b) { return a + b;}
double average(const double *values, int count) { double sum = 0; for (int i = 0; i < count; i++) sum += values[i]; return count > 0 ? sum / count : 0;}In Zig, declare the two functions and call them:
const std = @import("std");
extern fn add(a: c_int, b: c_int) c_int;extern fn average(values: [*]const f64, count: c_int) f64;
pub fn main() void { std.debug.print("add(2, 3) = {d}\n", .{add(2, 3)});
const temps = [_]f64{ 18.5, 21.0, 19.5 }; const avg = average(&temps, temps.len); std.debug.print("average = {d}\n", .{avg});}Now hand both files to Zig. It compiles the C file with its built-in Clang and links everything into one program:
zig run main.zig mathlib.cYou’ll see:
add(2, 3) = 5average = 19.666666666666668Notes on the declarations:
- This time it’s plain
extern fn, notextern "c" fn. The functions aren’t in libc; they’re inmathlib.c, which becomes part of your program. - C’s
const double *valuespoints to an array, so the Zig side says[*]const f64.&temps(a pointer to an array of 3f64) coerces to it. temps.lenis known at compile time, so it fits into ac_intwithout a cast.
mathlib.c doesn’t use the C standard library, so no -lc was needed. A C file that does #include <stdio.h> needs libc, and without -lc Clang can’t even find the header:
greet.c:1:10: error: 'stdio.h' file not found#include <stdio.h> ^~~~~~~~~~The same thing in build.zig
Section titled “The same thing in build.zig”For anything bigger than a quick test, put it in the build script (Zig Build System explains the basics). Here’s a project with Zig code in src/ and C code in c/, where c/greet.c uses printf:
const std = @import("std");
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
const exe_mod = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .link_libc = true, // greet.c uses printf }); exe_mod.addCSourceFiles(.{ .root = b.path("c"), .files = &.{ "mathlib.c", "greet.c" }, .flags = &.{ "-std=c99", "-Wall", "-Wextra" }, }); exe_mod.addIncludePath(b.path("c"));
const exe = b.addExecutable(.{ .name = "app", .root_module = exe_mod, }); b.installArtifact(exe);
const run_step = b.step("run", "Run the app"); const run_cmd = b.addRunArtifact(exe); run_step.dependOn(&run_cmd.step);}With extern fn greet(name: [*:0]const u8) void; added to main.zig and a greet("Zig"); at the end of main, zig build run prints:
add(2, 3) = 5average = 19.666666666666668Hello, Zig! (from C)What each new piece does:
.link_libc = trueon the module is thebuild.zigversion of-lc.addCSourceFilescompiles several C files:.rootis the folder,.filesthe names in it,.flagsthe C compiler flags. For one file there’s alsoaddCSourceFile(.{ .file = b.path("c/mathlib.c") }).addIncludePathtells the C compiler where to look for#include "..."headers.
The C code is compiled for the same target and optimize mode as your Zig code, so zig build -Dtarget=x86_64-windows cross-compiles the C part too.
Let Zig read the header: the translate-c package
Section titled “Let Zig read the header: the translate-c package”Writing extern declarations by hand is fine for three functions. For a header with fifty functions, structs, enums and #define constants, you want Zig to translate the header for you.
Until Zig 0.16 that was the @cImport builtin. It was deprecated in 0.16 and is removed in 0.17, where it’s now simply unknown:
main.zig:1:11: error: invalid builtin function: '@cImport'const c = @cImport({ ^~~~~~~~The 0.17.0 release notes explain the replacement: C translation now lives in the official translate-c package, which you add to your project like any other dependency (Zig Packages & Dependencies covers dependencies in general). It’s the same translator as before, with more options, and it can be updated separately from the compiler.
Step 1: add the package. In your project folder:
zig fetch --save git+https://codeberg.org/ziglang/translate-c#zig-0.17.xThat adds an entry like this to build.zig.zon (the commit and hash change as the branch gets updates):
.dependencies = .{ .translate_c = .{ .url = "git+https://codeberg.org/ziglang/translate-c?ref=zig-0.17.x#cfac21f3199b2b02ce3fd7db652aa456421fe4ab", .hash = "translate_c-2.0.2-Q_BUWvBNBwDnyehSiuAJmdFcMYHYGA-Jc3KiYdrV2Dqx", },},The zig-0.17.x branch is the one that matches Zig 0.17; other branches track other Zig versions.
Step 2: translate the header in build.zig. The package gives you a Translator helper. It turns a C header into a Zig module you can import:
const std = @import("std");const Translator = @import("translate_c").Translator;
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
// Turn mathlib.h into a Zig module. const translate_c = b.dependency("translate_c", .{}); const mathlib_h: Translator = .init(translate_c, .{ .c_source_file = b.path("c/mathlib.h"), .target = target, .optimize = optimize, });
const exe_mod = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "mathlib", .module = mathlib_h.mod }, }, }); exe_mod.addCSourceFile(.{ .file = b.path("c/mathlib.c") });
const exe = b.addExecutable(.{ .name = "app", .root_module = exe_mod, }); b.installArtifact(exe);
const run_step = b.step("run", "Run the app"); const run_cmd = b.addRunArtifact(exe); run_step.dependOn(&run_cmd.step);}Step 3: import it. No more hand-written extern lines. We also added #define MATHLIB_MAX_VALUES 100 to mathlib.h to show that simple macros come through as constants:
const std = @import("std");const mathlib = @import("mathlib");
pub fn main() void { std.debug.print("add(2, 3) = {d}\n", .{mathlib.add(2, 3)});
const temps = [_]f64{ 18.5, 21.0, 19.5 }; std.debug.print("average = {d}\n", .{mathlib.average(&temps, temps.len)}); std.debug.print("max values: {d}\n", .{mathlib.MATHLIB_MAX_VALUES});}zig build run prints:
add(2, 3) = 5average = 19.666666666666668max values: 100The first build takes a few seconds longer, because the translator itself gets compiled. After that it’s cached.
Linking a library installed on your system
Section titled “Linking a library installed on your system”The most common case: a C library you installed with your package manager, like zlib (on Debian or Ubuntu, apt install zlib1g-dev). You need its header for the declarations and its library file for the code. Put the header in a one-line file, src/c.h:
#include <zlib.h>Then translate it and tell the translator which system library to link:
const std = @import("std");const Translator = @import("translate_c").Translator;
pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{});
const translate_c = b.dependency("translate_c", .{}); const c: Translator = .init(translate_c, .{ .c_source_file = b.path("src/c.h"), .target = target, .optimize = optimize, .link_system_libs = &.{ .{ .name = "z" }, }, });
const exe = b.addExecutable(.{ .name = "crc", .root_module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "c", .module = c.mod }, }, }), }); b.installArtifact(exe);
const run_step = b.step("run", "Run the app"); const run_cmd = b.addRunArtifact(exe); run_step.dependOn(&run_cmd.step);}.{ .name = "z" } means libz, the same name you’d pass to a C compiler as -lz. The translator links libc by default, which zlib needs. Now call zlib from Zig:
const std = @import("std");const c = @import("c");
pub fn main() void { std.debug.print("zlib version: {s}\n", .{c.zlibVersion()});
const text = "hello, zlib"; const checksum = c.crc32(0, text, text.len); std.debug.print("crc32(\"{s}\") = {x}\n", .{ text, checksum });}On the Linux machine we tested on, zig build run printed:
zlib version: 1.3crc32("hello, zlib") = 15d0ba82(Your version line shows whatever zlib you have installed.) Naming the module c and writing c.crc32(...) is a common habit: you can see at a glance which calls go to C. In build.zig without translation, the same linking is exe_mod.linkSystemLibrary("z", .{}).
Upgrading code that used @cImport
Section titled “Upgrading code that used @cImport”Older code looks like this, all inside a .zig file:
const c = @cImport({ @cInclude("stdio.h"); @cInclude("zlib.h");});The move to 0.17 is mechanical:
- Put the includes in a header, e.g.
src/c.hwith#include <stdio.h>and#include <zlib.h>. - Run
zig fetch --save git+https://codeberg.org/ziglang/translate-c#zig-0.17.x. - In
build.zig, create aTranslatorforsrc/c.h, move anylinkSystemLibrarycalls into its.link_system_libs, and addtranslator.modas an import named"c". - Replace the
@cImportblock withconst c = @import("c");.
The rest of the code (c.printf, c.crc32 and so on) stays the same. (In 0.16 there was also a built-in b.addTranslateC step. It still exists in 0.17 but is deprecated in favor of the package.)
When translation doesn’t work out
Section titled “When translation doesn’t work out”Translation handles normal C well, but C headers can get wild. Things to expect:
- Simple
#defineconstants come through as Zig constants. Function-like macros sometimes can’t be translated. You get a declaration that’s a@compileError("unable to translate macro: ..."), which only fails if you actually use it. Write that one by hand in Zig. - Structs whose fields are hidden in the header become
opaquetypes: you can only hold pointers to them (Zig Opaque Types). - Pointers become
[*c]T. You can pass normal Zig pointers in; for values you get back, check for null (if (ptr == null)) or convert to a proper Zig pointer type before using them.
If a header is giving you trouble and you need only a few functions, writing the extern declarations by hand is always an option.
Practice
Section titled “Practice”1. Add a C function
Section titled “1. Add a C function”Add int multiply(int a, int b) to mathlib.c (and its header), declare it in main.zig with extern fn, and print multiply(6, 7). Build with zig run main.zig mathlib.c.
Hint: the declaration is the same shape as add.
Show solution
In mathlib.c:
int multiply(int a, int b) { return a * b;}In main.zig:
const std = @import("std");
extern fn multiply(a: c_int, b: c_int) c_int;
pub fn main() void { std.debug.print("multiply(6, 7) = {d}\n", .{multiply(6, 7)});}You’ll see:
multiply(6, 7) = 42Add the prototype int multiply(int a, int b); to mathlib.h too, so C code (and translate-c) knows about it.
2. Spot the missing piece
Section titled “2. Spot the missing piece”A project’s build.zig compiles c/log.c, which starts with #include <stdio.h>. The build fails with 'stdio.h' file not found. What’s missing?
Hint: which library does stdio.h belong to?
Show solution
The module needs libc. Add .link_libc = true to b.createModule(.{ ... }):
const exe_mod = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .link_libc = true,});Without libc, Zig doesn’t give the C compiler any libc headers, so stdio.h can’t be found. On the command line, the same fix is -lc.
3. Upgrade an @cImport
Section titled “3. Upgrade an @cImport”Rewrite this for Zig 0.17 so the Zig file becomes const c = @import("c");. List the files you’d change and what goes in each.
const c = @cImport({ @cInclude("sqlite3.h");});// and in build.zig: exe.root_module.linkSystemLibrary("sqlite3", .{});Hint: follow the four steps from the upgrade section.
Show solution
src/c.hcontains#include <sqlite3.h>.- Run
zig fetch --save git+https://codeberg.org/ziglang/translate-c#zig-0.17.x. - In
build.zig:
const Translator = @import("translate_c").Translator;// inside build():const c: Translator = .init(b.dependency("translate_c", .{}), .{ .c_source_file = b.path("src/c.h"), .target = target, .optimize = optimize, .link_system_libs = &.{.{ .name = "sqlite3" }},});// and in the executable's module: .imports = &.{.{ .name = "c", .module = c.mod }},- In the Zig file:
const c = @import("c");.
The linkSystemLibrary call moves into .link_system_libs, because the translated module is now the thing that links the library.
zig run main.zig mathlib.c(orbuild-exe) compiles C files and Zig together; declare the C functions withextern fn.- In
build.zig:addCSourceFile/addCSourceFiles(with.flags),addIncludePath, and.link_libc = truefor C code that uses libc. @cImportis removed in 0.17. Use the translate-c package:zig fetch --save git+https://codeberg.org/ziglang/translate-c#zig-0.17.x, then aTranslatorinbuild.zig, then@import("c")..link_system_libslinks installed libraries like zlib (.{ .name = "z" }).zig translate-c header.hshows what Zig makes of a header; translated pointers are[*c]T.- Macros that can’t be translated become compile errors only if you use them; declare those by hand.
Next up: Zig as a C Compiler, using zig cc to build and cross-compile plain C projects.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- C translation moving to an external package (0.17.0 release notes): the upgrade guide from
addTranslateCto the package. - translate-c on Codeberg: the package’s README, its options and three example projects.
- @cImport moving to the build system (0.16.0 release notes): the first step of the change, with a before-and-after.
- C Translation CLI (0.17.1 reference): the
zig translate-ccommand and its flags. - Zig Build System guide: more on modules, C source files and linking.