Cross compiling GO


$ go version
go version go1.21.5 linux/amd64

I’m able to cross compile straight go to an arm target using:

export GOARCH=arm
export GOOS=linux
go build

The code compiles and the object runs on the target.

However, with CGO_ENABLED=1 I run into issues with the gcc compiler. I add the following:

export CC=aarch64-linux-gnu-gcc-8

In this case I get an error from the gcc compiler:

aarch64-linux-gnu-gcc: error: unrecognized command line option ‘-marm’

I can build if I set the architecture to arm64, but in this case the object file will not run on the target.

Also, I get uname -m

on the target. However, I’m unable to set GOARCH to armv7l.

My question is, is it possible to build targets with “C”: interfaces given these issues for the target?


You must use correct gcc for arm 32-bit (gcc-arm-linux-gnueabi, gcc-arm-linux-gnueabihf, …) , not 64-bit

Hello @Dante_Castagnoli,

The error you’re encountering (unrecognized command line option ‘-marm’) occurs because the -marm flag is not supported by the ARM64 (aarch64) architecture.
To resolve this, you need to specify the correct cross-compiler for CGO. Here’s how you can do it.

export CC=arm-linux-gnueabi-gcc

This sets the CC environment variable to use the appropriate C cross-compiler for ARM architecture.
When you set GOARCH=arm64, you’re targeting the ARM64 architecture, which is different from ARMv7 (armv7l).
ARM64 binaries won’t run on ARMv7 systems, and vice versa.
To build specifically for ARMv7 (armv7l), you should set GOARCH=arm and GOARM=7

export GOARCH=arm
export GOARM=7

This ensures that the generated binary is compatible with ARMv7 systems.
Yes, it’s possible to build targets with “C” interfaces even with these issues.
Make sure you’ve set the correct cross-compiler (arm-linux-gnueabi-gcc) and the appropriate architecture (arm with GOARM=7).
If your Go code uses CGO to interface with C libraries, it should work as expected.
After cross-compiling, transfer the binary to your ARMv7 target and test it.
Ensure that the target system has the necessary shared libraries (if any) for your Go program to run successfully.
Remember to adjust your environment variables (GOARCH, GOARM, and CC) accordingly, and you should be able to cross-compile successfully for ARMv7 with CGO-enabled interfaces