Calling C code
- Go course
- Advanced
- Lesson 14/68
- 4 min
Learn to call C functions with the import "C" block.
The preamble and C headers
The comment above import "C" (the preamble) can also contain #include lines, so you can call functions from the standard C library.
/*
#include <stdlib.h>
*/
import "C"
n := C.abs(-5) // 5There must be no blank line between the preamble and import "C"; with a blank line the comment isn't treated as C code.
#cgo directives
To link an external library, #cgo lines are used in the preamble:
/*
#cgo LDFLAGS: -lm
#include <math.h>
*/
import "C"
fmt.Println(C.sqrt(16)) // 4CFLAGS passes options to the compiler and LDFLAGS to the linker; pkg-config: can fetch library settings automatically.
Practice A standard C function
Add #include <stdlib.h> in the preamble. Print the result of C.abs(-12).
Starter code
package main
/*
// C kodu buraya
*/
import "C"
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
/*
#include <stdlib.h>
*/
import "C"
import "fmt"
func main() {
fmt.Println(C.abs(-12))
}Expected output
12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if you put a blank line between the preamble and <code>import "C"</code>?
- The code compiles faster
- The C code is compiled twice
- The comment isn't treated as C code and functions aren't found Correct answer
- Nothing changes
Explanation: cgo only accepts the comment directly adjacent to import "C" as the preamble; with a blank line C.function stays undefined.
2 Linker option
/*
#cgo ____: -lm
#include <math.h>
*/
import "C"
/*
#cgo LDFLAGS: -lm
#include <math.h>
*/
import "C"
Explanation: LDFLAGS passes library options such as -lm to the linker.
3 Preamble lines
| Term | Meaning |
|---|---|
#include <stdio.h> |
Adds a C header |
#cgo CFLAGS |
Compiler option |
#cgo LDFLAGS |
Linker option |
#cgo pkg-config |
Fetches settings automatically |