package playne

imports "programmer"

How To: Cross compile Golang for Android

Update 2022:

Since this was back in the Golang 1.4 days and I have now had reason to do this again, the steps are a little easier. For Golang 1.19 I made a handy Makefile

Here is a handy Makefile that will build a 32bit binary on an Ubuntu22.04 box

NDK=/usr/lib/android-sdk/ndk-bundle/
.PHONY: linux

# if you are fancy and have an NDK installed
android:
	CC="$(NDK)/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi21-clang" \
	CC_FOR_TARGET="$(NDK)/toolchains/llvm/prebuilt/linux-x86_64/bin/armv7a-linux-androideabi21-clang" \
	CGO_ENABLED=1 \
	GOOS=android \
	GOARCH=arm \
	go build

setup:
	sudo apt install google-android-ndk-installer

To build for the android platform (GOOS=android) you need to do the following:

I placed all the downloads into ~/dev

  1. Get a copy of Golang >= version 1.4 from https://golang.org/dl/
    • Unpack it into ~/dev
  2. Grab the latest copy of the Android NDK from https://developer.android.com/tools/sdk/ndk/index.html
    • Make it executable and run it (it unpacks into the current folder, so ~/dev)
  3. Time to get a copy of our platform NDK.
    export NDK_ROOT=~/dev/ndk-toolchain
    ./android-ndk-r10c/build/tools/make-standalone-toolchain.sh --platform=android-16 --install-dir=$NDK_ROOT
        
  4. Now we need to build the Golang toolchain, cd into ~/dev/go/src
    export NDK_CC=~/dev/ndk-toolchain/bin/arm-linux-androideabi-gcc
    CC_FOR_TARGET=$NDK_CC GOOS=android GOARCH=arm GOARM=7 ./make.bash
        
  5. Now we can cross compile
    • You can put the following into a build.sh file
    • export NDK_TOOLCHAIN=~/dev/ndk-toolchain
      export CC=$NDK_TOOLCHAIN/bin/arm-linux-androideabi-gcc
      export GOROOT=~/dev/go
      export GOPATH=`pwd`
      export GOOS=android
      export GOARCH=arm
      export GOARM=7
      export CGO_ENABLED=1
      
      GO="$GOROOT/bin/go"
      
      $GO build -x main.go
      
    • Once you have made it executable (chmod +x build.sh) you can ./build.sh to build your app.

Posted

in

by

Tags: