Untuk platform Windows saat ini (end of 2023) CGO golang bisa di-compile menggunakan GCC tetapi tidak pada Vistual Studio 2022. Sehingga perlu untuk install gcc toolchain pada MSYS2/UCRT64.
Installing GCC Toolchain
$ pacman -S --needed base-devel mingw-w64-ucrt-x86_64-gcc
Install golang
Method 1: Using msys2 golang, but the version may be not updated.
$ pacman -S mingw-w64-ucrt-x86_64-go
- Update windows GOROOT environment:
C:\msys64\ucrt64\lib\go - Update windows GOPATH environment:
%USERPROFILE%\go - Append windows PATH environment:
%USERPROFILE%\go\bin
Method 2: Using official build, the version updated. (Recommended)
Go to: https://go.dev/dl/, then install to default location eg. C:\Go
Update the PATH environment to let msys/ucrt64 know where golang installed.
$ echo 'export PATH=/c/Go/bin:$PATH' >> ~/.bashrc
Implicitly the installer will set windows environment variable for
- set GOPATH environment:
%USERPROFILE%\go - append PATH environment:
C:\Go\bin;%USERPROFILE%\go\bin
On Msys/Ucrt64 also add this to allow msys execute go tools installed by go install:
$ echo "export PATH=$(cygpath $(go env GOPATH))/bin:\$PATH" >> ~/.bashrc
You may be need to remove msys/ucrt64 golang since you won’t using it, OR you can unset GOROOT since the msys/ucrt64 set this value in /ucrt64/etc/profile.d/go.sh, then:
$ echo 'unset GOROOT' >> ~/.bashrc
Update Git Executable Path
If you using Git for windows, then:
$ echo 'export PATH=/c/Program\ Files/Git/bin:$PATH' >> ~/.bashrc
Trying CGO using Msys/Ucrt64
For example we will try to compile project using CGO such as go-gl.
git clone https://github.com/gopxl/pixel
Try execute go list --json and no DepsErrors field shown:
{
"DepsErrors": [
{
"Err": "build constraints exclude all Go files in ..."
}
]
}
Executing using Command Prompt
You need to set PATH environment before compiling:
> set PATH=%PATH%;C:\msys64\ucrt64\bin
GOPLS Settings CGO For VSCode
For Gopls language server know where the GCC compiler, update the settings.json:
"gopls": {
"build.env": {
"PATH": "%PATH%;C:\\msys64\\ucrt64\\bin"
}
}
MSYS/UCRT64 Terminal FOR VSCode
"terminal.integrated.profiles.windows": {
"ucrt64 (MSYS2)": {
"path": "C:\\msys64\\msys2_shell.cmd",
"args": [
"-defterm", "-here", "-no-start", "-ucrt64"
]
}
}
Linking to C Libraries
You need to compile those libraries using GCC, not using Visual Studio 2022.