新来到这里。试图从C调用go函数但遭遇了一些编译问题
这是go脚本
package main
// #cgo CFLAGS: -Wno-error=implicit-function-declaration
// #include <stdlib.h>
// #include "wrapper.c"
import "C"
//import "unsafe"
import "fmt"
//import "time"
//export dummy
func dummy() int {
fmt.Println("hi you");
return 0
}
func main() {
C.testc()
}
这是包装器
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int dummy();
void testc(){
dummy();
}
运行时,出现错误
xyz@xyz-HP:~/learn/go$ go run reader.go
# command-line-arguments
In file included from $WORK/command-line-arguments/_obj/_cgo_export.c:2:0:
reader.go:30:14: error: conflicting types for ‘dummy’
In file included from reader.go:3:0,
from $WORK/command-line-arguments/_obj/_cgo_export.c:2:
./wrapper.c:6:12: note: previous declaration of ‘dummy’ was here
/tmp/go-build528677551/command-line-arguments/_obj/_cgo_export.c:8:7: error: conflicting types for ‘dummy’
In file included from reader.go:3:0,
from $WORK/command-line-arguments/_obj/_cgo_export.c:2:
./wrapper.c:6:12: note: previous declaration of ‘dummy’ was here
答案 0 :(得分:1)
您不需要在C文件中声明dummy
。这是我如何拆分代码以使其工作。我将C函数导出到.h
文件中,并将正文本身放在.c
文件中,并且只包含go代码中的h文件。
<强> dummy.h 强>:
void testc();
<强> dummy.c 强>:
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
void testc(){
dummy();
}
<强> main.go 强>:
package main
// #cgo CFLAGS: -Wno-error=implicit-function-declaration
// #include <stdlib.h>
// #include "dummy.h"
import "C"
import "fmt"
//export dummy
func dummy() int {
fmt.Println("hi you")
return 0
}
func main() {
C.testc()
}