How to Integrate Go Functions into Existing C Projects: A Step-by-Step Guide with Solutions for Linking Errors?

Susan Sarandon
Release: 2024-10-27 12:10:02
Original
1035 people have browsed it

How to Integrate Go Functions into Existing C Projects: A Step-by-Step Guide with Solutions for Linking Errors?

How to Use Go in Existing C Projects

Integrating Go Functions into C Programs

Integrating Go functions into C programs involves building a Go file into an object file (.o) and incorporating it into the existing C project's archive (.a) file. This allows calling Go functions from within the C program.

Issues Encountered in Example Code

The example provided by the user showcases errors during the linking phase. These errors stem from a misunderstanding where GCCGO expects a main function in the Go file, unlike the C program.

Solution with Go 1.5 and Beyond

In Go 1.5 and later versions, this issue is addressed. It enables building C-compatible libraries using the Go tool. With this feature, the user can keep the C file (main.c) as given in the question, and update the Go file (main.go) as follows:

<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>
Copy after login

Building a Go Object File

To build the Go file into an object file, run the following command:

go build -buildmode c-archive -o mygopkg.a
Copy after login

Integrating into C Project

To link the Go object file with the C program (_main.c), use the following command to build the final binary:

gcc -o main _main.c mygopkg.a -lpthread
Copy after login

Alternative Approach for Shared Libraries

If you prefer to build a shared library with Go, the following command will create mygopkg.so:

go build -buildmode c-shared -o mygopkg.so
Copy after login

To link the shared library with _main.c, run this command:

LD_RUN_PATH=$(pwd) gcc -o main _main.c mygopkg.so -lpthread
Copy after login

Note: Set LD_RUN_PATH to ensure the linker locates the shared library in the current directory during runtime.

For further details and insights, refer to the Go execution modes design document.

The above is the detailed content of How to Integrate Go Functions into Existing C Projects: A Step-by-Step Guide with Solutions for Linking Errors?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template