All posts

Zig / Cross-compile C/C++ and Zig programs

Posted On 01.07.2022

Zig came with a built-in C/C++ compiler zig cc and zig c++. So you can compile and run your C/C++ code with Zig!

For example, let’s compile this simple C program:

#include <stdio.h>
 
int main() {
  printf("Hello, World!!!");
  return 0;
}
zig cc hello.c -o hello

What’s more interesting is, cross-compiling works out of the box with Zig’s C compiler, for example, you can compile the above hello.c program for MacOS:

zig cc -target x86_64-macos -o hello-mac hello.c

Or for Linux:

zig cc -target x86_64-linux-musl -o hello-linux hello.c

It does not just work for this toy C program, but also for many C/C++ projects, for example, Zig’s author Andrew Kelley showed how he compiled LuaJIT and test them via QEMU in his article: https://andrewkelley.me/post/zig-cc-powerful-drop-in-replacement-gcc-clang.html

And not only Zig’s C/C++ compiler, but the Zig compiler itself can do cross-compile by supplying -target param:

zig build-exe -target x86_64-linux-musl hello.zig