What is cgo?
- Go course
- Advanced
- Lesson 13/68
- 4 min
Learn the ability to call C code with cgo.
What is cgo?
cgo is the tool that lets a Go program call C functions. The comment block right above the import "C" line is compiled as C code, and you reach its functions as C.name.
/*
int topla(int a, int b) { return a + b; }
*/
import "C"
fmt.Println(C.topla(2, 3)) // 5This is how mature C libraries such as SQLite and OpenSSL are used from Go.
The cost of cgo
cgo calls are far more expensive than normal Go calls (tens of nanoseconds of overhead). Cross-compiling also gets harder and producing a single static binary becomes difficult. Hence the saying: "cgo is not Go". If a pure-Go alternative exists (e.g. modernc.org/sqlite), it is considered first.
Practice Call a C function
In the preamble comment define int kare(int x) { return x * x; }. In main, print the result of C.kare(7) with fmt.Println.
Starter code
package main
/*
// C kodu buraya
*/
import "C"
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
/*
int kare(int x) { return x * x; }
*/
import "C"
import "fmt"
func main() {
fmt.Println(C.kare(7))
}Expected output
49
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is needed to build a package that uses cgo?
- Only the Go compiler
- A Java virtual machine
- Docker
- A C compiler on the system (gcc/clang) Correct answer
Explanation: cgo calls gcc or clang to compile the C code; with CGO_ENABLED=0 files that use cgo are not built.
2 Import the C package
/*
int iki() { return 2; }
*/
import "____"
/*
int iki() { return 2; }
*/
import "C"
Explanation: The special "C" package exposes the C code in the comment above it to Go.
3 cgo parts
| Term | Meaning |
|---|---|
import "C" |
Enables cgo |
The preamble comment |
C source code |
C.topla |
A C function call |
CGO_ENABLED=0 |
Disables cgo |