简体   繁体   中英

golang: cgo extern is not working

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()\n");
    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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM