`go build` 与 `go build file.go`

`go build` versus `go build file.go`

我在构建一个非常简单的通过 cgo 调用 c 代码的 go 程序时遇到了问题。 我的设置:

$: echo $GOPATH
/go
$: pwd
/go/src/main
$: ls
ctest.c  ctest.h  test.go

test.go 包含: 主包

// #include "ctest.c"
// #include <stdlib.h>
import "C"
import "unsafe"
import "fmt"

func main() {
  cs := C.ctest(C.CString("c function"))
  defer C.free(unsafe.Pointer(cs))
  index := "hello from go: " + C.GoString(cs)
  fmt.Println(index)
}

ctest.h 包含:

char* ctest (char*);

ctest.c 包含:

#include "ctest.h"

char* ctest (char* input) {
  return input;
};

当我 运行 go build test.go 我得到一个二进制文件,test 我可以 运行 打印预期的 hello from go: c function

但是当我 运行 go build 我得到错误:

# main
/tmp/go-build599750908/main/_obj/ctest.o: In function `ctest':
./ctest.c:3: multiple definition of `ctest'
/tmp/go-build599750908/main/_obj/test.cgo2.o:/go/src/main/ctest.c:3: first defined here
collect2: error: ld returned 1 exit status

不在 go build test.go 中的 go build 发生了什么导致错误?

仔细阅读你的代码。阅读错误消息。更正您的错误:

// #include "ctest.h"

test.go:

package main

// #include "ctest.h"
// #include <stdlib.h>
import "C"
import "unsafe"
import "fmt"

func main() {
  cs := C.ctest(C.CString("c function"))
  defer C.free(unsafe.Pointer(cs))
  index := "hello from go: " + C.GoString(cs)
  fmt.Println(index)
}

ctest.h:

char* ctest (char*);

ctest.c:

#include "ctest.h"

char* ctest (char* input) {
  return input;
};

输出:

$ rm ./test
$ ls
ctest.c  ctest.h  test.go
$ go build
$ ls
ctest.c  ctest.h  test  test.go
$ ./test
hello from go: c function
$