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:
Mark Functions for Export:
Compile Go Archive:
Compile the Go code into a C-callable static library using the following command:
go build -buildmode=c-archive foo.go
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
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!