Dynamic Linking in Go Binaries
Problem:
Consider a scenario where you have an existing Go binary and need to add functionality by compiling an external Go file. Once compiled, you want to integrate this new code into the binary without rebuilding the entire application.
Solution:
In Go 1.5 and later, it is now possible to build and link shared libraries dynamically. Here's how you can achieve your desired functionality:
$ go install -buildmode=shared std
This command builds the standard library as shared libraries.
Compile the external Go file as follows:
$ go build -linkshared hello.go
Once the external Go file is compiled, it can be linked into the existing binary using the -linkshared flag:
$ go install -linkshared mybinary.go
Within the existing binary, you can now call the newly compiled code like any other function defined in the binary itself.
Example:
package main import ( "fmt" "github.com/myimportpath/mypackage" ) func main() { fmt.Println("Before calling compiled code") mypackage.RunFoo() fmt.Println("After calling compiled code") }
The above is the detailed content of How Can I Dynamically Link External Go Code into an Existing Go Binary?. For more information, please follow other related articles on the PHP Chinese website!