How to Statically Link a C Library in Go Using Cgo
There are numerous discussions within the Go community on how to statically link a C library in Go using Cgo. However, it's important to note that this process is different from the syntax used in the Cgo documentation.
To statically link a C library, follow these steps:
Step 1: Modify Cgo Directives
In your Go code, include the following Cgo directives:
// #cgo CFLAGS: -I/path/to/c/include // #cgo LDFLAGS: /path/to/c/build/libgb.a
Replace "/path/to/c/include" with the path to the C header file and "/path/to/c/build/libgb.a" with the path to your statically linked C library.
Step 2: Compile and Link
Compile and link your Go program using the following command:
CGO_ENABLED=0 go build -a -installsuffix cgo -ldflags '-s'
Ensure that "-s" is included in the "ldflags" argument, as this strips symbols from the linked binary.
If you encounter errors like "not defined," ensure that the symbol exists in your C library.
Note: If you're using Go 1.0, static linking is not supported. Update to Go 1.1 or later for this functionality to work properly.
The above is the detailed content of How to Statically Link a C Library in Go Using cgo?. For more information, please follow other related articles on the PHP Chinese website!