Hello C, I’m called Go.

Writing applications in Go is a great experience, the language is easy to read and lets you handle your own errors like a big boy!

One issue I have come across, which rears its ugly head whenever I learn a slightly immature language is the need to reinvent the wheel. Take image conversion for instance, there are several libraries available for PHP, Python, C and the like so why should I have to rewrite everything!Step in cgo, a C linker and compiler for Go. This allows you to write a set of methods in C, using C libraries, and then make use of them in your Go application. Check out the classic “Hello World!” application below.

package main

// #include <stdio.h>
// int hello()
// {
//     printf("Hello Go, my name is C.");
//     getchar();
//     return 0;
// }
import "C"

func main() {
	C.hello()
}

Here you can see the way that a C application is integrated into Go. The Go source file is defined as main and the C module is imported before the main() go function is defined and the hello() method is called.

When you are writing a C program it needs to go above the imports and must be commented out with the “//” comment block. It must also be immediately followed by an independent ‘import “C”‘ in order for the application to compile correctly.

You can now go ahead and run this Go program in the same way you would any other:

go run src/hello-c.go

Good Go-ing and hope this little on has helped.

This post has been viewed 1507 times.

Leave a Reply

Your email address will not be published. Required fields are marked *