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

时间:2018-01-26 04:58:30

标签: go cgo

我无法构建一个非常简单的go程序,通过cgo调用c代码。 我的设置:

$: 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中没有go build test.go发生了什么?

1 个答案:

答案 0 :(得分:3)

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

// #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
$