Home >Backend Development >Golang >How can I Call Go Functions from My C Program Using GCCGO?
Calling Go Functions from a C Program Using GCCGO
Introduction
To integrate Go code within an existing C project, one must create an object file (.o) from the Go file and incorporate it into the C project's archive (.a) file. This article provides a detailed explanation on how to accomplish this using GCCGO.
Building a Go Object File
To create an object file from a Go file, use the gccgo command with the -c option to compile the file without linking it:
gccgo -c printString.go -o printString.o -fgo-prefix=print -Wall -Werror -march=native
The -fgo-prefix option specifies a prefix for the symbols exported from the Go file.
Linking the Go Function to the C Program
To link the Go object file to the C program, use extern declarations and the __asm__ keyword in the C code:
<code class="c">#include <stdio.h> extern int PrintString(char*) __asm__ ("print.main.PrintString");</code>
This declares the PrintString function with the correct signature and symbol name for GCCGO.
Compilation
To compile the C program with the Go object file, use gccgo with the -o option to specify the output executable:
gccgo -o main c_caller.c printString.o -Wall -Werror -march=native
Addressing Compilation Errors
The initial compilation error mentioned in the original question indicates that GCCGO expects a main function in the Go file. However, this is not required when linking to a C program. To resolve this issue, ensure that:
Additional Options
To address the linker errors related to missing library references, try the following options:
Example from Go 1.5 (August 2015)
Go 1.5 introduced the ability to build C-compatible libraries directly using the go tool. This method simplifies the process significantly:
_main.c
<code class="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; }</code>
main.go
<code class="go">package main import "C" import "fmt" //export PrintString func PrintString(cs *C.char) { s := C.GoString(cs) fmt.Println(s) } func main() {}</code>
Building as a Static Library:
go build -buildmode c-archive -o mygopkg.a gcc -o main _main.c mygopkg.a -lpthread
Building as a Shared Library:
go build -buildmode c-shared -o mygopkg.so LD_RUN_PATH=$(pwd) gcc -o main _main.c mygopkg.so -lpthread
The above is the detailed content of How can I Call Go Functions from My C Program Using GCCGO?. For more information, please follow other related articles on the PHP Chinese website!