For people who stumble upon this while searching for how to create an iOS framework or library in Go, you can use cgo
to compile GoLang into a c library and header file.
Compiler
To do this, you have to export some Go-compiler environment variables and set the CGO_ENABLED=1
flag to enable cgo
.
For iOS, you have to enable Bitcode (which reduces binary size), and set the architecture to be arm64
(or amd64
for iOS Simulator), and set the OS as darwin
. If you are running on the Simulator, you'll also want to set your SDK
to iphonesimulator
.
Then you pass some parameters to your go build
command to say -buildmode c-archive
to generate a C header file and -trimpath
to remove the path information.
All together, that looks like this:
$ export SDK=iphonesimulator
$ export GOOS=darwin
$ export GOARCH=arm64
$ export CGO_ENABLED=1
$ export CGO_CFLAGS="-fembed-bitcode"
$ go build -buildmode c-archive -trimpath -o outputFilename.a .
Code
You'll also have to do a couple things in your Go code.
- You must import the "C" module
import "C"
- You must export any functions you want to expose through the C header file by decorating these functions with the
//export functionName
comment.
//export functionName
func functionName() {
// do something
}
- If you are passing variables around, make sure you use the
C
data types, not the GoLang object types for these variables. So string
becomes C.CString
. For example:
//export helloWorld
func helloWorld() *C.char {
return C.CString("Hello world")
}
There's a blog article about this topic at Compile GoLang as a Mobile Library