Monday, January 23, 2012

simplest cgo program

Have been struggling to make a simple cgo sample to get familiar on how to link c code and go library.

Finally made it working.

cgo_test.go
-------------------------------
package cgo_test

/*
#include

void out() {
printf("Hello world from c\n");
}
*/
import "C"

func Out() {
C.out()
}

--------------------------------------------------------
main.go
--------------------------------------------------------
package main

import "cgo_test"

func main() {
cgo_test.Out()
}

--------------------------------------------------------
Makefile
--------------------------------------------------------
include ../go/src/Make.inc

TARG=cgo_test
CGOFILES=cgo_test.go

CLEANFILES+=main
include ../go/src/Make.pkg

main: install main.go
$(GC) main.go
$(LD) -o $@ main.$O

The most annoy error message I got is something like:
gomake main
main.go:6: cannot refer to unexported name cgo_test.out
main.go:6: undefined: cgo_test.out

It seems that GO only export Initcap names by default.

No comments: