Home >Backend Development >Golang >How Can I Call Go Functions from a C Program Using Go 1.5's `-buildmode=c-archive`?

How Can I Call Go Functions from a C Program Using Go 1.5's `-buildmode=c-archive`?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 19:53:13672browse

How Can I Call Go Functions from a C Program Using Go 1.5's `-buildmode=c-archive`?

Calling Go Code from a C Program with Go 1.5

In Go 1.5, the -buildmode=c-archive feature was introduced to bridge Go code into non-Go environments. With this feature, you can integrate Go code into an existing C project, enabling you to delegate higher-level tasks to the more verbose Go.

Exporting Go Functions for C Invocation

To make Go functions available to C code, you must explicitly export them using special //export comments.

package main

import (
    "C"
    "fmt"
)

//export PrintInt
func PrintInt(x int) {
    fmt.Println(x)
}

func main() {}

Compiler Configuration for C Usage

Compiling the Go code as a C-callable library requires using the -buildmode=c-archive flag.

go build -buildmode=c-archive foo.go

This command generates a static library (foo.a) and a header file (foo.h) containing the exported function declaration.

Integrating into a C Project

Within your C project, include the generated header file and use the provided function as follows:

#include "foo.h"

int main(int argc, char **argv) {
    PrintInt(42);
    return 0;
}

Compilation and Execution

To compile the C program, use the -pthread flag for proper thread support.

gcc -pthread foo.c foo.a -o foo

Running the executable will now print the intended integer (42) to the console.

The above is the detailed content of How Can I Call Go Functions from a C Program Using Go 1.5's `-buildmode=c-archive`?. 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