Home >Backend Development >Golang >How to Integrate Go Functions into Existing C Projects Using GCCGO?
Using Go Within Existing C Projects
Background:
You have a C program comprised of multiple object files stored in an archive file (.a). You intend to add a new Go file to the project, compile it into an object file, and incorporate it into the existing archive.
Objective:
Integrate Go functions into your C program.
Process:
1. Compile the Go File into an Object File:
Run the following command:
gccgo -c printString.go -o printString.o -fgo-prefix=print -Wall -Werror -march=native
2. Call Go Functions from C:
In your c_caller.c file, declare an extern function:
extern int PrintString(char*) __asm__ ("print.main.PrintString");
In the main function, call the Go function and handle the result:
int result = PrintString(string_to_pass); if (result) { printf("Everything went as expected!\n"); } else { printf("Uh oh, something went wrong!\n"); }
3. Using GCCGO to Build the Entire Project:
Run the following command:
gccgo -o main c_caller.c printString.o -Wall -Werror -march=native
4. Addressing Errors:
Alternative Solution in Go 1.5:
In Go 1.5 (coming in August), a new feature enables the creation of C-compatible libraries from Go code. With this feature, you can build a static or shared library directly from a Go file, eliminating the need for intermediate object files.
Example:
In main.c:
#include <stdio.h> int main() { char *string_to_pass = NULL; if (asprintf(&string_to_pass, "This is a test.") < 0) { printf("asprintf fail"); return -1; } PrintString(string_to_pass); return 0; }
In main.go (compiled with go build -buildmode c-archive ... for static or go build -buildmode c-shared ... for shared library):
package main import "C" import "fmt" //export PrintString func PrintString(cs *C.char) { s := C.GoString(cs) fmt.Println(s) } func main() {}
The above is the detailed content of How to Integrate Go Functions into Existing C Projects Using GCCGO?. For more information, please follow other related articles on the PHP Chinese website!