亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Set GOOS and GOOSARCH for Target Platforms
Automate Builds for Multiple Platforms
Watch Out for CGO and External Dependencies
Use Build Tags to Handle Platform-Specific Code
Home Backend Development Golang Cross-Compiling Go Applications for Different Platforms

Cross-Compiling Go Applications for Different Platforms

Jul 28, 2025 am 03:45 AM
go Cross-compilation

Go makes cross-compilation extremely simple. You only need to set GOOS and GOARCH environment variables to generate binary files of the target platform; 1. Use GOOS and GOARCH to specify the target operating system and architecture, such as linux, windows, darwin, amd64, arm64, etc.; 2. Use GOOS=target system GOARCH=target architecture go build command to generate executable files for the corresponding platform; 3. Use shell scripts or Makefile to automate multi-platform construction processes to improve efficiency; 4. Ensure CGO_ENABLED=0 to avoid cross-compilation problems caused by CGO dependency; 5. Use Go's build tag (//go:build) to handle specific code logic of different operating systems. The appropriate files will be automatically selected according to the target platform. The entire process does not require an additional tool chain, and multi-platform compilation can be completed from a single machine.

Cross-Compiling Go Applications for Different Platforms

Go makes cross-compiling applications incredibly straightforward thanks to its built-in support for multiple operating systems and architectures. Unlike many other languages, you don't need complex toolchains or external dependencies—just a single command can produce binaries for different platforms.

Cross-Compiling Go Applications for Different Platforms

Here's how to effectively cross-compile Go applications.


Set GOOS and GOOSARCH for Target Platforms

Go uses environment variables GOOS (target operating system) and GOARCH (target architecture) to control cross-compilation. You don't need to install anything extra—Go's toolchain includes compilers for many platforms.

Cross-Compiling Go Applications for Different Platforms

Common values:

  • GOOS (Operating Systems):
    linux , windows , darwin (macOS), freebsd , openbsd , android , etc.

    Cross-Compiling Go Applications for Different Platforms
  • GOARCH (Architectures):
    amd64 , 386 , arm , arm64 , riscv64 , etc.

To build a Linux 64-bit binary on a macOS or Windows machine:

 GOOS=linux GOARCH=amd64 go build -o myapp-linux main.go

For a Windows executable:

 GOOS=windows GOARCH=amd64 go build -o myapp.exe main.go

And for macOS on Apple Silicon (arm64):

 GOOS=darwin GOARCH=arm64 go build -o myapp-mac main.go

These commands can be run from any development machine—no need for a target OS.


Automate Builds for Multiple Platforms

If you need to support several platforms, manually running commands gets tedious. Use a script or Makefile to automate.

Example shell script:

 #!/bin/bash

set -e

version="1.0.0"
mkdir -p releases

build() {
  os=$1
  arch=$2
  ext=""
  if [ "$os" = "windows" ]; then
    ext=".exe"
  fi
  echo "Building for $os/$arch..."
  GOOS=$os GOARCH=$arch go build -o "releases/myapp-$version-$os-$arch$ext" main.go
}

# Build for common platforms
build linux amd64
build linux arm64
build windows amd64
build darwin amd64
build darwin arm64

Now a single ./build.sh gives you binaries for deployment across environments.


Watch Out for CGO and External Dependencies

Cross-compilation works flawlessly as long as you avoid CGO . If your code (or a dependency) uses CGO—like calling C libraries—you'll run into issues because it requires platform-specific C compilers.

By default, CGO is disabled when cross-compiling, which is usually fine unless you're using packages like:

  • sqlite3 (with CGO bindings)
  • gopsutil (some features)
  • Custom C extensions

To ensure CGO stays off:

 CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o app main.go

If you must use CGO, you'll need cross-compiling C toolchains (like x86_64-linux-gnu-gcc ), which complicates things significantly. For maximum portability, prefer pure Go implementations.


Use Build Tags to Handle Platform-Specific Code

Sometimes your app needs different logic per OS (eg, file paths, system calls). Use build tags to include/exclude code during compilation.

Example: windows_setup.go

 //go:build windows
// build windows

package main

func init() {
    println("Running on Windows")
}

And unix_setup.go :

 //go:build darwin || linux
// build darwin,linux

package main

func init() {
    println("Running on Unix-like system")
}

Go automatically includes the right files based on GOOS . No extra configuration needed.


Cross-compiling in Go is simple, reliable, and part of the standard workflow. Just set GOOS and GOARCH , keep CGO disabled unless necessary, and automate with scripts. Whether you're shipping CLI tools, microservices, or desktop apps, Go lets you target nearly any platform from a single machine.

Basically, that's all it takes.

The above is the detailed content of Cross-Compiling Go Applications for Different Platforms. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Building and Deploying Go Applications with Docker Building and Deploying Go Applications with Docker Jul 25, 2025 am 04:33 AM

Usemulti-stageDockerbuildstocreatesmall,secureimagesbycompilingtheGobinaryinabuilderstageandcopyingittoaminimalruntimeimagelikeAlpineLinux,reducingsizeandattacksurface.2.Optimizebuildperformancebycopyinggo.modandgo.sumfirsttoleverageDockerlayercachin

A Guide to Go's Templating Engine A Guide to Go's Templating Engine Jul 26, 2025 am 08:25 AM

Go's template engine provides powerful dynamic content generation capabilities through text/template and html/template packages, where html/template has automatic escape function to prevent XSS attacks, so it should be used first when generating HTML. 1. Use {{}} syntax to insert variables, conditional judgments and loops, such as {{.FieldName}} to access structure fields, {{if}} and {{range}} to implement logical control. 2. The template supports Go data structures such as struct, slice and map, and the dot in the range represents the current iterative element. 3. The named template can be defined through define and reused with the template directive. 4.ht

Integrating Go with Kafka for Streaming Data Integrating Go with Kafka for Streaming Data Jul 26, 2025 am 08:17 AM

Go and Kafka integration is an effective solution to build high-performance real-time data systems. The appropriate client library should be selected according to needs: 1. Priority is given to kafka-go to obtain simple Go-style APIs and good context support, suitable for rapid development; 2. Select Sarama when fine control or advanced functions are required; 3. When implementing producers, you need to configure the correct Broker address, theme and load balancing strategy, and manage timeouts and closings through context; 4. Consumers should use consumer groups to achieve scalability and fault tolerance, automatically submit offsets and use concurrent processing reasonably; 5. Use JSON, Avro or Protobuf for serialization, and it is recommended to combine SchemaRegistr

How to pass a slice to a function in Go? How to pass a slice to a function in Go? Jul 26, 2025 am 07:29 AM

When passing slices in Go, it is usually passed directly by value, because the slice header contains a pointer to the underlying array, and copying the slice header will not copy the underlying data, so the modification of elements in the function will affect the original slice; 1. If you need to reassign or adjust the slice length within the function and make the change take effect, you should pass the slice pointer; 2. Otherwise, you can pass the slice directly without using a pointer; 3. If reallocation may be triggered when using append, you must pass through the pointer to make the updated slice visible to the outside. Therefore, unless the entire slice is to be replaced, the slice should be passed in the form of a value.

what does go vet do what does go vet do Jul 26, 2025 am 08:52 AM

govetcatchescommonlogicalerrorsandsuspiciousconstructsinGocodesuchas1)misuseofprintf-stylefunctionswithincorrectarguments,2)unkeyedstructliteralsthatmayleadtoincorrectfieldassignments,3)sendingtoclosedchannelswhichcausespanics,4)ineffectiveassignment

how to handle signals go by example how to handle signals go by example Jul 25, 2025 am 04:36 AM

Use signal.Notify() in the os/signal package to register the specified signal (such as SIGINT, SIGTERM) into the buffer channel, so that the program can be captured instead of terminated by default; 2.

How to use reflection in Go? How to use reflection in Go? Jul 28, 2025 am 12:26 AM

Usereflect.ValueOfandreflect.TypeOftogetruntimevaluesandtypes;2.Inspecttypedetailswithreflect.TypemethodslikeName()andKind();3.Modifyvaluesviareflect.Value.Elem()andCanSet()afterpassingapointer;4.CallmethodsdynamicallyusingMethodByName()andCall();5.R

How to embed a file into a string in Go? How to embed a file into a string in Go? Jul 26, 2025 am 05:40 AM

To embed the file contents into the string of the Go program, you should use go:embed (Go1.16) to embed the file at compile time; 1. Add the //go:embed directive above the target variable; 2. Ensure the file path is correct and the file exists; 3. Use string type variables to receive text content; 4. Build the project through gobuild to include the file content. This method is safe and efficient and does not require additional tools, and ultimately implements the file contents directly into the binary file as strings.

See all articles