Zack Scholl

zack.scholl@gmail.com

go and zig

 / #golang #zig 

amazing incantations for easily using CGo by leveraging zig.

In 2020 it became possible to very easily compile CGo using zig’s drop-in replacement for GCC/Clang. For me, this is the biggest game changer in Go for a few years.

windows magic

on windows, you no longer need to install TDM-GCC or MinGW-w64 to develop against CGo. Using scoop you can simply install zig:

1scoop install zig

and then your CGo build will just work with the following command:

1$env:CGO_ENABLED=1; $env:CC="zig cc"; go build -v -x

I was having so many troubles with weird errors in MinGW-w641 and this just worked.

linux magic

the linux situation is even more incredible.

one of the common things I want to do is cross-compile for windows from linux. zig also makes this super easy with -target:

1CGO_ENABLED=1 CC="zig cc -target x86_64-windows-gnu" \
2    GOOS=windows GOARCH=amd64 go build -v -x

even more magical is the Mac OSX situation, which was terribly riddled with strange errors and requires it’s own SDK. luckily, Jose Quintana is hosting MacOS X SDK’s which can be used to compile against Mac OS X in a simple Makefile incantation:

 1build: MacOSX11.3.sdk
 2	MACOS_MIN_VER=11.3 MACOS_SDK_PATH=$(PWD)/MacOSX11.3.sdk \
 3        CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 \
 4	CGO_LDFLAGS="-mmacosx-version-min=$${MACOS_MIN_VER} --sysroot $${MACOS_SDK_PATH} -F/System/Library/Frameworks -L/usr/lib" \
 5	CC="zig cc -target aarch64-macos -isysroot $${MACOS_SDK_PATH} -iwithsysroot /usr/include -iframeworkwithsysroot /System/Library/Frameworks" \
 6	go build -ldflags "-s -w" -buildmode=pie -v -x 
 7
 8MacOSX11.3.sdk:
 9	wget https://github.com/joseluisq/macosx-sdks/releases/download/11.3/MacOSX11.3.sdk.tar.xz
10	tar -xvf MacOSX11.3.sdk.tar.xz

the Mac OS X incantation itself is a little more involved because it has to grab the Frameworks library and I only learned about it from Luca Corbo’s post detailing it and other one-liners. but again, it just works.

github actions

the best for last - all of these tools work perfectly well in Github Actions. I am working on a project that is compiled for all OS’s, using CGo, and I now have a Github action that automatically builds new releases.


  1. I stopped trying to debug errors once I found this zig incantation, but here is the MinGW-w64 error I was getting: error: '__format__' attribute argument not supported: gnu_scanf [-Werror,-Wignored-attributes] __attribute__((__format__ (gnu_scanf, 2, 3))) __MINGW_ATTRIB_NONNULL(2) ↩︎