Go言語を使って、M1 MacとIntel Macの両方に対応したコマンドの作り方。
なでしこ3配布キットで、mac用のバイナリは、ユニバーサルバイナリとした。作り方を忘れそうだったのでここにメモ。
最初にMacで対応アーキテクチャを調べる方法
file
コマンドで確認できる。
$ file (コマンド)
例えば以下のように表示される。
% file nadesiko3
nadesiko3: Mach-O universal binary with 2 architectures: [x86_64:Mach-O 64-bit executable x86_64] [arm64]
nadesiko3 (for architecture x86_64): Mach-O 64-bit executable x86_64
nadesiko3 (for architecture arm64): Mach-O 64-bit executable arm64
Go言語で特定CPU向けのバイナリを作る
簡単に言うと、go build
コマンドでarm64
とamd64
のバイナリを作っておいて、lipo
コマンドでユニバーサルバイナリに結合する。以下のような感じで。
APP_NAME=hoge
ROOT_DIR=./src
OUT_DIR=./bin
ARM=$OUT_DIR/$APP_NAME.arm64
AMD=$OUT_DIR/$APP_NAME.amd64
# 各種CPU向けバイナリを生成
cd $ROOT_DIR
GOOS=darwin GOARCH=amd64 go build -o $ARM
GOOS=darwin GOARCH=arm64 go build -o $AMD
# 結合する
cd $OUT_DIR
lipo -create -output $APP_NAME $ARM $AMD
なお、注意点だが、この記事を書いた時点で、lipoを使う時は、ディレクトリが出力ディレクトリが同一でないとうまく動かなかった。何時間もはまった。