我在构建一个非常简单的go程序时遇到了麻烦,它通过cgo调用c代码。我的设置:
$: echo $GOPATH
/go
$: pwd
/go/src/main
$: ls
ctest.c ctest.h test.go
test.go包含: package
// #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)
}
H包含:
char* ctest (char*);
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
发生了什么?
发布于 2018-01-26 06:38:33
仔细阅读你的代码。读取错误消息。纠正您的错误:
// #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
$
https://stackoverflow.com/questions/48456009
复制相似问题