Home >Backend Development >Golang >Can Go binaries dynamically load and link externally compiled Go code at runtime?
Problem Statement:
Given a compiled Go binary, is it possible to dynamically compile an external Go file and link it into the existing binary for immediate execution?
Solution:
The ability to create shared libraries, which enable dynamic loading and linking, was introduced in Go version 1.5 in August 2015.
Steps to Build and Link Dynamically:
Create Shared Library:
Compile the external Go file as a shared library using the -buildmode=shared flag:
go install -buildmode=shared my_library.go
Build Binary with Dynamic Linking:
Compile the Go binary that will load and link the shared library using the -linkshared flag:
go build -linkshared main.go
Example:
Consider the following code in main.go:
package main import ( "fmt" "plugin" ) func main() { p, err := plugin.Open("my_library.so") if err != nil { fmt.Println(err) return } runFoo, err := p.Lookup("RunFoo") if err != nil { fmt.Println(err) return } runFoo.(func())() // Call the exported function from the shared library }
Note: The shared library must export the function RunFoo using //export RunFoo in the Go source code.
The above is the detailed content of Can Go binaries dynamically load and link externally compiled Go code at runtime?. For more information, please follow other related articles on the PHP Chinese website!