~/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:
- Use
import "C"
after the C code comment. - You can call C functions as
C.functionName()
. - Use
go run
orgo build
as usual. - Your system must have a C compiler installed.
To pass values between Go and C, use these types:
C.int
,C.double
, etc map to C types.- Use
C.CString(goString)
for passing Go strings to C.
For more complex use, see the cgo documentation. For cross compiling, check the FAQ.
Read more on calling C code from Go.