~/Running C Code in Golang

Feb 15, 2025


Golang can run C code using the cgo tool. This enables calling C functions directly from Go, useful for performance or reusing legacy code.

First, add a special comment to your Go file to include C code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
/*
#include <stdio.h>
#include <stdlib.h>
void hello() {
    printf("Hello from C\n");
}
*/
import "C"

func main() {
    C.hello()
}

To pass values between Go and C, use these types:

For more complex use, see the cgo documentation. For cross compiling, check the FAQ.

Read more on calling C code from Go.

Tags: [golang] [c] [integration] [ffi]