From 58b017f565f9f31c20cf32db5a98754b339aff24 Mon Sep 17 00:00:00 2001 From: DaanSelen Date: Thu, 4 Dec 2025 14:06:09 +0100 Subject: [PATCH] chore: add information cross compile docs --- cross-compile.md | 68 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 cross-compile.md diff --git a/cross-compile.md b/cross-compile.md new file mode 100644 index 0000000..e53a240 --- /dev/null +++ b/cross-compile.md @@ -0,0 +1,68 @@ +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. Here’s 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. It’s 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 + +Here’s 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. \ No newline at end of file