Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building and linking dynamically from a go binary

Tags:

My problem is the following:

  1. I have a go binary on a machine
  2. From that binary I need to compile an external .go file
  3. Once compiled, I need to link the compiled go file into the current binary so I can use the just-compiled go code.

Do you think that's possible ?

I did a few researches and it does not seem to be possible, but I might have overlooked something.

Thanks :)

The first go binary would contain something like

func main() {
    // Here I need to compile an external go file (or package) which contains
    // The definition of runFoo()

    // Once the file/package is compiled and linked I need to call the compiled code
    runFoo()

    // Continue the execution process normally here
}
like image 463
Jérôme R Avatar asked Oct 17 '13 15:10

Jérôme R


People also ask

Does Go support dynamic linking?

Go does not currently support dynamic linking.

What is a dynamically linked binary?

All the code and dependencies needed is contained within the binary itself. Whereas dynamically-linked binaries rely on shared-libraries for parts of their functionality. This allows processes to share code and eliminates the need to store shared library code in every executable.

What is dynamic linking with example?

Dynamic linking means that the code for some external routines is located and loaded when the program is first run. When you compile a program that uses shared libraries, the shared libraries are dynamically linked to your program by default.

How do you use dynamic linking?

Dynamic linking is a two-step process that relies on accessing the addresses of code. The first step occurs at compilation. When a file is compiled with a dynamic library, instead of copying the actual object code contained in the library, the linker simply scans the code contained and checks for missing symbols.


1 Answers

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.

like image 168
Dave C Avatar answered Sep 17 '22 17:09

Dave C