go-sqlite3 icon indicating copy to clipboard operation
go-sqlite3 copied to clipboard

cross compile from Mac to Linux

Open batara666 opened this issue 3 years ago • 6 comments

> go version
go version go1.18.1 darwin/arm64
> GOOS=linux GOARCH=amd64 CGO_ENABLED=1 go build -trimpath
# runtime/cgo
linux_syscall.c:67:13: error: implicit declaration of function 'setresgid' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
linux_syscall.c:67:13: note: did you mean 'setregid'?
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/unistd.h:593:6: note: 'setregid' declared here
linux_syscall.c:73:13: error: implicit declaration of function 'setresuid' is invalid in C99 [-Werror,-Wimplicit-function-declaration]
linux_syscall.c:73:13: note: did you mean 'setreuid'?
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/unistd.h:595:6: note: 'setreuid' declared here

batara666 avatar May 12 '22 13:05 batara666

Your C compiler seems not support cross compiling for Linux.

mattn avatar May 12 '22 14:05 mattn

I ended up using Docker. I don't know much about it, but I managed. Command:

docker buildx build --platform=linux/amd64 --target bin --output bin/ .

And here's the important part for from dockerfile:


FROM --platform=$BUILDPLATFORM golang:latest AS build

WORKDIR /src

RUN apt-get update 
RUN apt-get install -y gcc-multilib

ENV CGO_ENABLED=1
ARG TARGETOS TARGETARCH

RUN --mount=target=. \
    --mount=type=cache,target=/root/.cache/go-build \
    --mount=type=cache,target=/go/pkg \
    GOOS=$TARGETOS GOARCH=$TARGETARCH go build -o /out/fillip_linux ./cmd

FROM scratch as bin

COPY --from=build /out/fillip_linux ./fillip_linux

malaschitz avatar May 18 '22 18:05 malaschitz

You can use zig as a cross-compiler (many references on the internet how to do it). I am on linux/amd64, so will cross-compile _examples/simple to linux/arm64:

go-sqlite3/_example/simple$ CC="zig cc -target aarch64-linux-musl" GOOS=linux GOARCH=arm64 CGO_ENABLED=1 go build -trimpath  .
go-sqlite3/_example/simple$ file simple
simple: ELF 64-bit LSB executable, ARM aarch64, version 1 (SYSV), static-pie linked, Go BuildID=v0J3H_Y7IQRiQ26cF8Rb/DJMzPVHNAPPpixbjkZNj/Ej2fxeIvLwu1tw80enDk/nnoFyKfir37KeWzAv6b0, with debug_info, not stripped
go-sqlite3/_example/simple$ qemu-aarch64-static ./simple | head -10
0 こんにちわ世界000
1 こんにちわ世界001
2 こんにちわ世界002
3 こんにちわ世界003
4 こんにちわ世界004
5 こんにちわ世界005
6 こんにちわ世界006
7 こんにちわ世界007
8 こんにちわ世界008
9 こんにちわ世界009

You can also use, for example, -target aarch64-linux-gnu.2.32 (or so) to link against glibc 2.32 instead of producting a musl-based static binary.

motiejus avatar Jul 20 '22 05:07 motiejus