This repository demonstrates how to integrate Go code into a macOS Swift application
using static linking via Go’s c-archive mode.
The project showcases how Go functions can be compiled into a C-compatible
static library and then called directly from Swift through a bridging header.
All implementation details, technical explanations, and code examples are documented here: Full Implementation Documentation.
Unlike older approaches that relied on dynamically loading Go .so files,
modern Xcode versions no longer allow external dynamic libraries of this type.
The correct and supported method is to compile Go code as a
static archive (.a) along with a generated
C header (.h).
These files are then imported into Swift using a bridging header, allowing the Swift macOS application to call Go-exported functions as if they were native C functions.
- Go Code: Go functions exported via cgo using the C ABI. The Go code is compiled into
libfibonacci.aand a generated headerlibfibonacci.h. - Swift macOS Project: A macOS application written in Swift that statically links the Go library and calls the exported Go function through the bridging header.
- Go Source (fibonacci.go): Written in Go, exported using
//exportand compiled viac-archiveto produce a static library and header. - Static Library Build: The Go code is compiled into
libfibonacci.aandlibfibonacci.h, which are added to the macOS project. - Bridging Header: The generated header is included in the Xcode bridging header so Swift can recognize the exported C symbols.
- Swift macOS App: Calls the Go function directly through the imported symbol exposed by the bridging header.
Go’s cgo toolchain can export Go functions using the C ABI. When compiled using the
c-archive build mode, Go produces a static library (.a) plus a C header file.
The Swift macOS project imports the header through a bridging header, allowing the app to
invoke Go functions as if they were plain C functions. This enables the Swift app to
use computational logic written in Go while maintaining a native macOS UI.
Run the following command inside the Go source directory:
go build -buildmode=c-archive -o libfibonacci.a .
Add libfibonacci.a and libfibonacci.h to the Xcode project.
Include libfibonacci.h in the bridging header so that Swift can see the exported symbols.
The Swift code can then call the Go function directly through the C interface.
- macOS: Fully supported using static linking.
- iOS: Not supported with
c-archive; requiresgomobile bind.
