How to Integrate Go Functions into an Existing C Project using GCCGO?

Mary-Kate Olsen
Release: 2024-10-26 20:36:03
Original
480 people have browsed it

How to Integrate Go Functions into an Existing C Project using GCCGO?

Using Go in an Existing C Project

You aim to integrate Go functions into a C program by creating an object file from a Go source file and including it in an existing C project. However, you encounter linking errors despite using GCCGO.

To address this issue, as suggested by the solution, consider the following approach:

For Go 1.5 and later, use the -buildmode flag to create C-compatible libraries:

  • Static library:

    go build -buildmode c-archive -o mygopkg.a
    Copy after login
  • Shared library:

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

Once you have the C-compatible library, you can integrate it into your C project:

  • Static library:

    gcc -o main _main.c mygopkg.a -lpthread
    Copy after login
  • Shared library:

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

Note that LD_RUN_PATH ensures that the linker finds the shared library in the current directory.

Using this approach, you can create C-compatible libraries in Go and seamlessly integrate them into existing C projects, allowing you to call Go functions from within your C program.

The above is the detailed content of How to Integrate Go Functions into an Existing C Project using GCCGO?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!