首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >“`go”与“`go file.go`”

“`go”与“`go file.go`”
EN

Stack Overflow用户
提问于 2018-01-26 04:58:29
回答 1查看 232关注 0票数 1

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

代码语言:javascript
运行
复制
$: echo $GOPATH
/go
$: pwd
/go/src/main
$: ls
ctest.c  ctest.h  test.go

test.go包含: package

代码语言:javascript
运行
复制
// #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包含:

代码语言:javascript
运行
复制
char* ctest (char*);

C包含:

代码语言:javascript
运行
复制
#include "ctest.h"

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

当我运行go build test.go时,我得到一个二进制文件,test,它可以运行,它将打印出所需的hello from go: c function

然而,当我运行go build时,我得到了错误:

代码语言:javascript
运行
复制
# 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发生了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-26 06:38:33

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

代码语言:javascript
运行
复制
// #include "ctest.h"

test.go

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
char* ctest (char*);

ctest.c

代码语言:javascript
运行
复制
#include "ctest.h"

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

输出:

代码语言:javascript
运行
复制
$ 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
$ 
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48456009

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档