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

How to call c code in golang

(*-*)浩
Release: 2019-12-31 13:14:31
Original
3110 people have browsed it

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()
}
Copy after login
Execute the program:

go run main.go
Copy after login

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 代码
Copy after login
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"
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template