Building and linking dynamically from a go binary

Update: It is now possible to do this in mainline Go, see Go Execution Modes

From the Go 1.5 release notes:

For the amd64 architecture only, the compiler has a new option, -dynlink, that assists dynamic linking by supporting references to Go symbols defined in external shared libraries.

Old Answer (useful discussion of other options):

It is not currently possible to create dynamically linked libraries* in main line Go. There has been some talk about this, so you may see support in the future. However, there is a 3rd party go project called goandroid that needed the same functionality you need, so they maintain patches that should allow you to patch the official Go code base to support the dynamic linked support you are requesting.

If you want to use a the standard Go run-time, I would recommend the one of the following. Invoke your Go program from your other program, and communicate using:

  1. Pipes to communicate
  2. A UNIX domain socket
  3. An mmaped region of shared memory.
    1. That is, create a file on /dev/shm and have both programs mmap it.
    2. The Go mmap library: https://github.com/edsrzf/mmap-go

Each consecutive option will take more effort to setup, be more platform specific, but potentially be more powerful than the previous one.

*Note: That is, DLLs in the Windows world, and .so files in the UNIX/Linux world.


The ability to create shared libraries will be in Go 1.5 in August 2015¹.

From "The State of Go" talk by Andrew Gerrand:

Shared libraries

Go 1.5 can produce Go shared libraries that can be consumed by Go programs.

Build the standard library as shared libraries:

$ go install -buildmode=shared std

Build a "Hello, world" program that links against the shared libraries:

$ go build -linkshared hello.go
$ ls -l hello
-rwxr-xr-x 1 adg adg 13926 May 26 02:13 hello

Go 1.5 can also build Go programs as C archive files (for static linking) or shared libraries (for dynamic linking) that can be consumed by C programs.

[See:] golang.org/s/execmodes

¹ Note, gccgo already had limited support for this for some time, Go 1.5 will be the first time this is supported by the regular go build tools.

Tags:

Go