I created the following script to compile a project as static in go, but I'm not getting a static executable.
PASTA=bin/scak_linuxAMD64
ARQUIVO=$PASTA/server_rest
export GOOS=linux
export GOARCH=amd64
export CGO_ENABLED=1
export CXX_FOR_TARGET=/usr/local/musl/bin/musl-gcc
export CC_FOR_TARGET=/usr/local/musl/bin/musl-gcc
export CC=/usr/local/musl/bin/musl-gcc
export CXX=/usr/local/musl/bin/musl-gcc
if [ -d $PASTA ]; then
rm -r $PASTA && echo -e "Limpado $PASTA\n"
fi
mkdir -p $PASTA 2> /dev/null
echo -e "Compilando para $GOOS:$GOARCH\n"
go build -v -o $ARQUIVO -a -ldflags '-extldflags "-static" -s'
if [ -f $ARQUIVO ]; then
echo -e "Gerado executável: $ARQUIVO"
echo -e "file: $(file $ARQUIVO)\n"
cp -r www $PASTA && zip -r $PASTA/dist.zip $PASTA && echo "Gerado arquivo dist.zip com executável e site"
fi
In this script I use musl as compiler c, which is previously installed. When I set the variable CGO_ENABLED = 0, the code compiles as static, but I need CGO enabled (= 1) because I use the library "github.com/mattn/go-sqlite3" that needs cgo to work.