从 c 调用 go 函数时出错

error on calling go function from c

第一次来这里。尝试从 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

您无需在 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()
}