Home  >  Article  >  Backend Development  >  How to call c code in golang

How to call c code in golang

(*-*)浩
(*-*)浩Original
2019-12-31 13:14:313102browse

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.go

The 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn