Home >Backend Development >Golang >How Can I Call Go Functions from a C Program Using Go 1.5's `-buildmode=c-archive`?
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.
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() {}
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.
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; }
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!