golang: cgo extern 不起作用

huangapple go评论85阅读模式
英文:

golang: cgo extern is not working

问题

我正在尝试运行带有以下示例的golang的cgo(在go-wiki -> Global Functions中给出):

foo.go 文件:

package gocallback

import "fmt"

/*
#include <stdio.h>
extern void ACFunction();
*/
import "C"

//export AGoFunction
func AGoFunction() {
        fmt.Println("AGoFunction()")
}

func Example() {
        C.ACFunction()
}

foo.c 文件:

#include "_cgo_export.h"
void ACFunction() {
    printf("ACFunction()\n");
    AGoFunction();
}

运行此示例时,我遇到以下错误:

# command-line-arguments
/tmp/go-build770916112/command-line-arguments/_obj/foo.cgo2.o: In function    `_cgo_3234419c4c2a_Cfunc_ACFunction':
./foo.go:36: undefined reference to `ACFunction'
collect2: ld returned 1 exit status

我无法追踪到这个问题。为什么 ACFunctionundefined?或者我漏掉了什么?

go version:
go version go1.1.2 linux/386

英文:

I am trying to run cgo for golang with following example (given at go-wiki -> Global Functions):

foo.go file:

package gocallback

import &quot;fmt&quot;

/*
#include &lt;stdio.h&gt;
extern void ACFunction();
*/
import &quot;C&quot;

//export AGoFunction
func AGoFunction() {
        fmt.Println(&quot;AGoFunction()&quot;)
}

func Example() {
        C.ACFunction()
}

foo.c file:

#include &quot;_cgo_export.h&quot;
void ACFunction() {
    printf(&quot;ACFunction()\n&quot;);
    AGoFunction();
}

While running this example, I am getting following error:

# command-line-arguments
/tmp/go-build770916112/command-line-arguments/_obj/foo.cgo2.o: In function    `_cgo_3234419c4c2a_Cfunc_ACFunction&#39;:
./foo.go:36: undefined reference to `ACFunction&#39;
collect2: ld returned 1 exit status

I am not able to trace this down. Why ACFunction is undefined? or Am I missing something?

go version:
go version go1.1.2 linux/386

答案1

得分: 8

根据问题的评论,似乎您尝试使用go run foo.go构建和运行程序。

这会导致一个go run: cannot run non-main package错误,但是将包名转换为main并添加一个main函数确实会重现问题中的错误。这似乎是因为它尝试编译只有foo.go文件而没有伴随的foo.c文件。

如果您将文件放在$GOPATH/src目录下的一个目录中,并使用go build packagename来构建程序,它应该成功构建包中的所有源文件。

英文:

Based on the question comments, it seems that you were trying to build and run the program with go run foo.go.

This fails with a go run: cannot run non-main package error, but converting the package name to main and adding a main function does reproduce the error in the question. This seems to be because it is trying to compile only the foo.go file and not the companion foo.c file.

If you instead place the files in a directory under $GOPATH/src and use go build packagename to build the program, it should successfully build all the source files in the package.

huangapple
  • 本文由 发表于 2013年12月11日 14:46:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/20512353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定