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
Release: 2024-12-17 18:48:13
Original
476 people have browsed it

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
      Copy after login
      Copy after login
    • 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"
      Copy after login
    • Link against the Go archive using the -pthread option:

      gcc -pthread foo.c foo.a -o foo
      Copy after login
      Copy after login
    • 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() {}
Copy after login

Compile it into an archive:

go build -buildmode=c-archive foo.go
Copy after login
Copy after login

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

#include "foo.h"

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

Compile it:

gcc -pthread foo.c foo.a -o foo
Copy after login
Copy after login

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!

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