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
Shared library:
go build -buildmode c-shared -o mygopkg.so
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
Shared library:
export LD_RUN_PATH=$(pwd) gcc -o main _main.c mygopkg.so -lpthread
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!