gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:57:17 36 4
gpt4 key购买 nike

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

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com