Search code examples
windowsgocgoexitstatus

golang cgo exit status 2 on Windows


Attempt

I want to compile the following snippet on my Windows 8.1 machine with Go 1.8.1 installed.

package main

/*
int theAnswer() {
    return 42;
}
*/
import "C"

import "fmt"

func main() {
    fmt.Println(C.theAnswer())
}

Here is a working Ideone Snippet.

Problem

Whilst running the snippet in ideone works as expected, the compilation on my own machine fails somehow:

$ CC=gcc GOARCH=amd64 GOOS=windows go build -x
WORK=C:\Users\****\AppData\Local\Temp\go-build775642990
mkdir -p $WORK\_\D_\dev\workspaces\go\src\github.com\nopmind\_obj\
mkdir -p $WORK\_\D_\dev\workspaces\go\src\github.com\nopmind\_obj\exe\
cd D:\dev\workspaces\go\src\github.com\nopmind

CGO_LDFLAGS="-g" "-O2" "C:\\Go\\pkg\\tool\\windows_amd64\\cgo.exe" 
-objdir "C:\\Users\\****\\AppData\\Local\\Temp\\go-build775642990\\_\\D_\\dev\\workspaces\\go\\src\\github.com\\nopmind\\_obj\\" 
-importpath _/D_/dev/workspaces/go/src/github.com/nopmind 
-- -I "C:\\Users\\****\\AppData\\Local\\Temp\\go-build775642990\\_\\D_\\dev\\workspaces\\go\\src\\github.com\\nopmind\\_obj\\" 
-g -O2 Test.go

go build _/D_/dev/workspaces/go/src/github.com/nopmind: C:\Go\pkg\tool\windows_amd64\cgo.exe: exit status 2

($ go build -x gives same output)

After googling for a few hours without any useful results I'm now hardstuck on this.

Environment

Question

Does anyone have a clue why this is happening ?

My personal guess is that something is wrong with the MingW installation. If so I'd appreciate a short explanation how to properly set MingW up for cgo.


Solution

  • Your code works on Windows 10 and 7 and Linux. For example, on Windows 10, using TDM-GCC for MinGW,

    Microsoft Windows [Version 10.0.15063]
    
    >go version
    go version devel +dc0f0ab Thu Apr 13 18:20:38 2017 +0000 windows/amd64
    
    >gcc --version
    gcc (tdm64-1) 5.1.0
    
    >type answer.go
    package main
    
    /*
    int theAnswer() {
        return 42;
    }
    */
    import "C"
    
    import "fmt"
    
    func main() {
            fmt.Println(C.theAnswer())
    }
    
    >go run answer.go
    42
    
    >
    

    I have never used Win-builds.