Introduction to CGO

CGO is the tool that makes it possible to run C code in a Go application. This feature has been around since Go reached version 1.0 in 2009 and allowed us to use existing C libraries when there were fewer packages available outside the standard library than today.

The C code is accessed through the C pseudo package, and it is accessed and called using the package name followed by the identifier, for instance, C.print.

The import declaration is preceded by a series of special comments, which specify what C source file the application should import:

package example

// #include <stdio.h>
import "C"

This statement can also be a multiline comment, which can contain more include directives, like the one from the example earlier, and even actual C code directly:

package example

/*
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

void someFunction(char* s) {
printf("%s\n", s);
}
*/
import "C"

It is important to avoid blank lines between the C comment and the import statement, otherwise the libraries and the code will be imported by CGO in the application.