Home >Backend Development >Golang >How to call c code in golang
#cgo makes it possible to use C code in Golang.
##Hello World A simple example, create the file main.go:
package main /* #include <stdio.h> void sayHi() { printf("Hi"); } */ import "C" func main() { C.sayHi() }Execute the program:
go run main.goThe program executes and outputs hi (for more examples, see $GOROOT/misc/ cgo).
Preparation work under Windows
If you want to use cgo on Windows, you need to install the gcc compiler. Here I use mingw-w64.Set compilation and link flags
What we use import "C" to import is a pseudo-package (pseudo-package), through which we use C code. Before import "C", the comment immediately following import "C" can include:编译器和链接器标志 C 代码We can set the compiler and linker flags through the #cgo directive, for example:
// #cgo CFLAGS: -DPNG_DEBUG=1 // #cgo amd64 386 CFLAGS: -DX86=1 // #cgo LDFLAGS: -lpng // #include <png.h> import "C"
The above is the detailed content of How to call c code in golang. For more information, please follow other related articles on the PHP Chinese website!