packetie
packetie

Reputation: 5069

error on calling go function from c

New to go here. Tried to call go function from C but suffered some compiling issues

Here is the go script

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()
}

Here is the wrapper

#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

extern int dummy();

void testc(){
    dummy();
}

When running it, got error

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

Upvotes: 1

Views: 1750

Answers (1)

Not_a_Golfer
Not_a_Golfer

Reputation: 49187

You don't need to declare dummy in your C file. Here's how I split your code to make it work. I put the C function exporting in an .h file, and the body itself in a .c file, and included only the h file in the go code.

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()
}

Upvotes: 1

Related Questions