Files
runesmith/cross-compile.md
DaanSelen 58b017f565
Some checks failed
Cross-Compile Binaries / compile-linux (push) Failing after 1m6s
Cross-Compile Binaries / compile-windows (push) Successful in 9m35s
chore: add information cross compile docs
2025-12-04 14:06:09 +01:00

68 lines
2.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
To cross-compile a Go program for Windows from Linux using CGO, you need to set the environment variables for the target OS and architecture, and specify the appropriate C and C++ compilers. For example, you can use the command: Google Wikipedia
GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CXX_FOR_TARGET=x86_64-w64-mingw32-g++ CC_FOR_TARGET=x86_64-w64-mingw32-gcc go build -o your_program.exe your_program.go
Cross Compiling Go Programs for Windows from Linux with CGO
Prerequisites
Go Installation: Ensure you have Go installed on your Linux system. Version 1.5 or higher is required for easy cross-compilation.
C Cross-Compiler: Install a cross-compiler for Windows. Use the following command to install mingw-w64:
bash
sudo apt-get install gcc-mingw-w64
Setting Up Environment Variables
To cross-compile a Go program that uses CGO, you need to set specific environment variables. Heres how to do it for both 32-bit and 64-bit Windows executables:
For 32-bit Windows:
bash
export GOOS=windows
export GOARCH=386
export CGO_ENABLED=1
export CXX=i686-w64-mingw32-g++
export CC=i686-w64-mingw32-gcc
For 64-bit Windows:
bash
export GOOS=windows
export GOARCH=amd64
export CGO_ENABLED=1
export CXX=x86_64-w64-mingw32-g++
export CC=x86_64-w64-mingw32-gcc
Building the Executable
Once the environment variables are set, you can build your Go program. Use the following command:
bash
go build -o your_program.exe your_program.go
Important Notes
Statefulness: The build process can be stateful. Its recommended to build Windows binaries last to avoid issues with Linux binaries.
Testing: You cannot run Windows executables directly on Linux. Use Wine to test your built executables.
Example Command
Heres a complete example for building a simple Go program:
bash
# Set environment for 64-bit Windows
export GOOS=windows
export GOARCH=amd64
export CGO_ENABLED=1
export CXX=x86_64-w64-mingw32-g++
export CC=x86_64-w64-mingw32-gcc
# Build the executable
go build -o hello.exe hello.go
This process allows you to create Windows executables from a Linux environment while utilizing CGO for C dependencies.