Home >Backend Development >Golang >Can Go binaries dynamically load and link externally compiled Go code at runtime?

Can Go binaries dynamically load and link externally compiled Go code at runtime?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 07:59:13786browse

Can Go binaries dynamically load and link externally compiled Go code at runtime?

Dynamic Loading and Linking from a Go Binary

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:

  1. Create Shared Library:

    • Compile the external Go file as a shared library using the -buildmode=shared flag:

      go install -buildmode=shared my_library.go
  2. 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!

Statement:
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