go and zig
amazing incantations for easily using CGo by leveraging 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.
on windows, you no longer need to install TDM-GCC or MinGW-w64 to develop against CGo. Using scoop you can simply install zig:
scoop install zig
and then your CGo build will just work with the following command:
$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.
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
:
CGO_ENABLED=1 CC="zig cc -target x86_64-windows-gnu" \
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:
build: MacOSX11.3.sdk
MACOS_MIN_VER=11.3 MACOS_SDK_PATH=$(PWD)/MacOSX11.3.sdk \
CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 \
CGO_LDFLAGS="-mmacosx-version-min=$${MACOS_MIN_VER} --sysroot $${MACOS_SDK_PATH} -F/System/Library/Frameworks -L/usr/lib" \
CC="zig cc -target aarch64-macos -isysroot $${MACOS_SDK_PATH} -iwithsysroot /usr/include -iframeworkwithsysroot /System/Library/Frameworks" \
go build -ldflags "-s -w" -buildmode=pie -v -x
MacOSX11.3.sdk:
wget https://github.com/joseluisq/macosx-sdks/releases/download/11.3/MacOSX11.3.sdk.tar.xz
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.
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.
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)
↩︎