How to execute C code from go – c to golang binding ?

package main

// If a Go source file imports “C”, it is using cgo. The Go file will have access to anything appearing in the comment immediately preceding the line import “C”, and will be linked against all other cgo comments in other Go files, and all C files included in the build process.

/*
#include stdio.h
#include stdlib.h

void myprint(char* s) {
    printf("This is in C code : %s\n", s);
}
*/
import "C"

note here: there should be no new line between closing comment (*/) and import “C” lines, like below

*/
new line
import "C"

this will result in error,
# command-line-arguments
could not determine kind of name for C.free
could not determine kind of name for C.myprint

import "unsafe"

func Example() {
cs := C.CString("This is passed from Go Code\n")
C.myprint(cs)
C.free(unsafe.Pointer(cs))
}

func main() {
Example()
}

//reference : https://github.com/golang/go/wiki/cgo

The complete source code for “main.go” is like below,

package main
/*
#include stdio.h
#include stdlib.h

void myprint(char* s) {
    printf("This is in C code : %s\n", s);
}
*/
import "C"

import "unsafe"

func Example() {
    cs := C.CString("This is passed from Go Code\n")
    C.myprint(cs)
    C.free(unsafe.Pointer(cs))
}

func main() {
	Example()
}

Compile the code as,

go build

If you are cross compiling same code, you can refer to post https://lynxbee.com/how-to-resolve-error-no-buildable-go-source-files-in/ and add CGO_ENABLED=1 before go build.

Leave a Comment