1

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

1 Answer 1

1

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()
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the quick reply. When I ran it, got error ./main.go:33: undefined reference to `testc'
@codingFun how did you run it? I ran it with go build -o dummy && ./dummy
go build invokes cgo behind the scenes, generating wrapper files etc etc. you can run cgo directly on the code to see what it does.
Thanks @Not_a_Golfer, I ran it as "go run main.go" and got the error with loader/ld. Ran it your way (using go build..), it works great. Thanks again. I have accepted your answer and upvoted it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.