I an building a c archive in my iOS project using following:
GOOS=ios GOARCH=arm64 CGO_ENABLED=1 SDK=iphonesimulator CGO_CFLAGS="-fembed-bitcode" CC=pwd/clangwrap.sh go build -buildmode=c-archive -o libuplink.a
Clangwrap.sh looks like this
#!/bin/sh
# go/clangwrap.sh
SDK_PATH=`xcrun --sdk $SDK --show-sdk-path`
CLANG=`xcrun --sdk $SDK --find clang`
if [ "$GOARCH" == "amd64" ]; then
CARCH="x86_64"
elif [ "$GOARCH" == "arm64" ]; then
CARCH="arm64"
fi
exec $CLANG -arch $CARCH -isysroot $SDK_PATH -mios-version-min=10.0 "$@"
When I link it up in XCode and attempt to run with simulator however, I can only run it on the device itself:
building for iOS Simulator, but linking in object file built for iOS ... for architecture arm64
How do I target the simulator for a go build for a static library that's used in Swift project?
Requirements
TL;DR
You could do something similar to Xcode if you choose a simulator as run destination.
So basically use something like
-target arm64-apple-ios16.2-simulatorinstead of-arch arm64. Also omit-mios-version-min=10.0, since the actual minimal version is encoded in the -target (e.g. 16.2), which takes precedence (the correct option for the simulator would be-miphonesimulator-version-minanyway).Then as
CGO_LDFLAGSalso specify the-targetoption plus-syslibrootwith the path to the SDK.Your build scripts tweaked a bit, it might look something like this:
This specifies the simulator as the target and the minimum version is 15.
build.sh
target.sh
clangwrap.sh
The
clangwrap.shthen simplifies to:Details
Different SDKs
Different SDKs must be specified for an iOS device and the iPhone simulator. You can find them next to the other platforms supported by Xcode under
/Applications/Xcode.app/Contents/Developer/Platforms. For example, in Xcode 14.2, among others, there is aniPhoneOSplatform with aniPhoneOS16.2.sdkand aniPhoneSimulatorplatform withiPhoneSimulator16.2.sdk.There is this interesting post from an Apple employee in the Apple developer forum: https://developer.apple.com/forums/thread/673387#662260022
To check a generated static library to display the
loadcommands, you can call:A static library generated for use with an Apple Silicon simulator should display something like the following:
Note:
platform 7denotes the simulator,minosthe minimum deployment target, andsdkthe actual SDK version used.See the section in the include file
loader.hthat reads:You can view them yourself on your system as follows:
Build for iPhone device
To build a static library for the iPhone SDK, you would change this:
in the
build.shscript above.If you tried to use this library in the simulator, it would fail with the message
building for iOS Simulator, but linking in object file built for iOS, file 'libuplink.a' for architecture arm64.The output of
otool -lwould read:Note:
Platform 2stands forPLATFORM_IOSand not for the simulator.This will of course run perfectly on the device.