douya1855 2013-12-11 06:46
浏览 140
已采纳

golang:cgo extern无法正常工作

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

foo.go file:

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 file:

#include "_cgo_export.h"
void ACFunction() {
    printf("ACFunction()
");
    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':
./foo.go:36: undefined reference to `ACFunction'
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条回答

  • douhuang1852 2013-12-11 08:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog