Writing to the Android Log

So I just figured out how to get my log messages from a system Golang program into the android log without the need for logwrapper.

It is a side effect of importing the “app” mobile package. so…

import (
	_ "golang.org/x/mobile/app"

The downside is that *everything* written via stdout will go to the system log – even flag.Usage()

If you want to go a little more serious, here is a nice chunk of code

package main

#cgo LDFLAGS: -llog
import "C"
import "unsafe"

func writeAndroidLogInfo(tag, message string) {
	ctag := C.CString(tag)
	cstr := C.CString(message)
	C.__android_log_write(C.ANDROID_LOG_INFO, ctag, cstr)

You can use it like so

writeAndroidLogInfo("MyIdentifier", "My Message")

and the output in logcat will be

I/MyIdentifier( 4444): My Message

How To: Cross compile Golang for Android

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 build -x main.go
    • Once you have made it executable (chmod +x build.sh) you can ./build.sh to build your app.

Cross Compile Golang on Ubuntu 14.04

So today I needed to cross compile a basic Golang app from linux/amd64 to linux/arm (for android) on my Ubuntu 14.04 box.

It is actually kinda easy

sudo apt-get install golang-go-linux-arm

because I am running the latest 1.3 golang i needed to run an extra step:

cd /usr/local/go/src/
sudo GOARCH=arm ./make.bash

Once you have that setup, it is as simple as:

you@host:~/golang/src/yourrepohost/yourrepos/repo$ GOARCH=arm go build

Golang – struct, make and the case of the missing variable

I made a rookie mistake last night. I forgot an asterisk in my code and it caused me a an hour of confusion!

TL;DR – methods on structs in golang need their stuct passed as a pointer if you want to modify it!

This works

func (f *Foo)SomeFunc() {}

This does not!

func (f Foo)SomeFunc() {}