Cross compile Go on OSX?

前端 未结 6 1675
生来不讨喜
生来不讨喜 2020-12-02 03:39

I am trying to cross-compile a go app on OSX to build binaries for windows and linux. I have read everything what I could find on the net. Closest example that I have found

6条回答
  •  隐瞒了意图╮
    2020-12-02 03:56

    The process of creating executables for many platforms can be a little tedious, so I suggest to use a script:

    #!/usr/bin/env bash
    
    package=$1
    if [[ -z "$package" ]]; then
      echo "usage: $0 "
      exit 1
    fi
    package_name=$package
    
    #the full list of the platforms: https://golang.org/doc/install/source#environment
    platforms=(
    "darwin/386"
    "dragonfly/amd64"
    "freebsd/386"
    "freebsd/amd64"
    "freebsd/arm"
    "linux/386"
    "linux/amd64"
    "linux/arm"
    "linux/arm64"
    "netbsd/386"
    "netbsd/amd64"
    "netbsd/arm"
    "openbsd/386"
    "openbsd/amd64"
    "openbsd/arm"
    "plan9/386"
    "plan9/amd64"
    "solaris/amd64"
    "windows/amd64"
    "windows/386" )
    
    for platform in "${platforms[@]}"
    do
        platform_split=(${platform//\// })
        GOOS=${platform_split[0]}
        GOARCH=${platform_split[1]}
        output_name=$package_name'-'$GOOS'-'$GOARCH
        if [ $GOOS = "windows" ]; then
            output_name+='.exe'
        fi
    
        env GOOS=$GOOS GOARCH=$GOARCH go build -o $output_name $package
        if [ $? -ne 0 ]; then
            echo 'An error has occurred! Aborting the script execution...'
            exit 1
        fi
    done
    

    I checked this script on OSX only

    gist - go-executable-build.sh

提交回复
热议问题