Home >Backend Development >Golang >How Can I Integrate Go Code into My Existing C Project?

How Can I Integrate Go Code into My Existing C Project?

DDD
DDDOriginal
2024-12-17 18:48:13477browse

How Can I Integrate Go Code into My Existing C Project?

Integrating Go Code into an Existing C Project

Question:
Is it possible to call Go code from a C program, and if so, how can this be achieved?

Answer:
Yes, Go 1.5 introduced the -buildmode=c-archive mode, which allows Go code to be compiled into an archive suitable for linking into C programs. To integrate Go code into an existing C project:

  1. Mark Functions for Export:

    • Functions intended to be called from C must be marked with //export comments in the Go code.
    • Ensure the Go package containing these functions is named main.
    • Include a function named main, even if it is empty.
    • Import the C package.
  2. Compile Go Archive:

    • Compile the Go code into a C-callable static library using the following command:

      go build -buildmode=c-archive foo.go
    • This will generate an archive and a header file (e.g., foo.a and foo.h).
  3. Link C Program:

    • In the C program, include the generated header file:

      #include "foo.h"
    • Link against the Go archive using the -pthread option:

      gcc -pthread foo.c foo.a -o foo
    • This will allow the C program to call the exported Go functions.

Example:

Consider the following Go code (foo.go):

package main

import "C"
import "fmt"

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

func main() {}

Compile it into an archive:

go build -buildmode=c-archive foo.go

Then, in a C program (foo.c):

#include "foo.h"

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

Compile it:

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

Running foo will print "42".

The above is the detailed content of How Can I Integrate Go Code into My Existing C Project?. 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