How to call C language functions in Golang?

WBOY
Release: 2024-03-20 16:03:03
Original
688 people have browsed it

How to call C language functions in Golang?

How to call C language functions in Golang?

During the development process, sometimes you will encounter situations where you need to call functions of the C language, and Golang provides a simple and efficient way to achieve this requirement. This article will introduce how to call C language functions in Golang and provide specific code examples.

First, we need to create a file containing C language code. For example, you can create a file named c_function.c in the project root directory. In this file, we will define the C language functions that need to be called, such as the following sample code:

#include <stdio.h>

void sayHello() {
    printf("Hello from C!
");
}

int add(int a, int b) {
    return a b;
}
Copy after login

Next, we need to call these C language functions in the Golang program. First, we need to create a Golang file named cgo_example.go and write the following code in the file:

package main

/*
#cgo CFLAGS: -g -Wall
void sayHello();
int add(int a, int b);
*/
import "C"
import "fmt"

func main() {
    // Call the C language function sayHello()
    C.sayHello()

    // Call the C language function add()
    a, b := 10, 20
    sum := C.add(C.int(a), C.int(b))
    fmt.Printf("The sum of %d and %d is %d
", a, b, int(sum))
}
Copy after login

In the above code, we use import "C" to import the C language package. Next, use the #cgo instruction below the import statement to tell the Golang compiler the C language code file that needs to be linked, and define the C language function that needs to be called in the subsequent comments. In the main function, we first called the C language function sayHello(), then called the C language function add() and printed the result.

In the command line, use the following command to compile and run the program:

go build -o cgo_example cgo_example.go
./cgo_example
Copy after login

The above is the specific implementation and code example of calling C language functions in Golang. By using CGo technology, we can easily integrate C language functions into Golang programs to achieve more flexible and powerful functions. Hope the above content is helpful to you!

The above is the detailed content of How to call C language functions 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