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

标签 go cgo

我在构建一个非常简单的通过 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
$ 

关于go - `go build` 与 `go build file.go`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48456009/

相关文章:

android - 在 Android.bp 中使用 Golang 在 "optional_subdirs"上应用条件?

CGo 将 go 字符串转换为 *C.uchar

戈朗 : cgo extern is not working

opengl - 使用 cgo 链接 Windows DLL

Go 例子和成语

go - 作为另一个用户执行

go - 在golang html/template中对 slice 进行排序?

go - 我们如何确定 "last"工作进程/线程在 Go 中何时完成?

c - 在 Golang 中释放 C 变量?

go - 如何在 Go 中填写 void* C 指针?