Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cornerot/0240488a9a497285f86480686083f59c to your computer and use it in GitHub Desktop.
Save cornerot/0240488a9a497285f86480686083f59c to your computer and use it in GitHub Desktop.
Create a sample shared library in golang 1.5.
nadeem@myznc:~/go/src$ ls -al dummy
total 12
drwxrwxr-x 2 nadeem nadeem 4096 Jul 20 18:46 .
drwxrwxr-x 6 nadeem nadeem 4096 Jul 20 18:45 ..
-rw-rw-r-- 1 nadeem nadeem 129 Jul 20 18:46 hello.go
nadeem@myznc:~/go/src/dummy$ cat hello.go
// Package dummy contains hello world library.
package dummy
import "fmt"
func RunFoo() {
fmt.Println("Hello World")
}
Here are the steps to build this package as a library:
a) In order to create library, we first need to compile & install runtime shared libraries:
go install -buildmode=shared runtime sync/atomic
This will install the create "linux_amd64_dynlink" under $GOROOT/pkg. Here is what directory looks like
nadeem@myznc:/usr/local/go/pkg/linux_amd64_dynlink$ ls -R
.:
libruntime,sync-atomic.so runtime runtime.a runtime.shlibname sync
./runtime:
cgo.a cgo.shlibname
./sync:
atomic.a atomic.shlibname
b) Now lets build our dummy library, we need to pass -linkshared flag in order to use the .so file created above
nadeem@myznc:~/go/src$ go build -linkshared -buildmode=shared dummy
c) Now lets install this library:
nadeem@myznc:~/go/src$ go install -linkshared -buildmode=shared dummy
nadeem@myznc:~/go/pkg/linux_amd64_dynlink$ ls -al
total 3080
drwxrwxr-x 2 nadeem nadeem 4096 Jul 20 19:06 .
drwxrwxr-x 3 nadeem nadeem 4096 Jul 20 19:06 ..
-rw-r--r-- 1 nadeem nadeem 7180 Jul 20 19:06 dummy.a
-rw-r--r-- 1 nadeem nadeem 12 Jul 20 19:06 dummy.shlibname
-rw-r--r-- 1 nadeem nadeem 3132538 Jul 20 19:06 libdummy.so
nadeem@myznc:~/go/pkg/linux_amd64_dynlink$ ldd libdummy.so
linux-vdso.so.1 => (0x00007ffc2d9b7000)
libruntime,sync-atomic.so => /usr/local/go/pkg/linux_amd64_dynlink/libruntime,sync-atomic.so (0x00007f9418e18000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9418a4e000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f941882f000)
/lib64/ld-linux-x86-64.so.2 (0x00007f94196a8000)
d) Now lets use this library
nadeem@myznc:~/go/src$ cat main.go
package main
import "dummy"
func main() {
dummy.RunFoo()
}
nadeem@myznc:~/go/src$ go build -linkshared main.go
nadeem@myznc:~/go/src$ ldd main
linux-vdso.so.1 => (0x00007ffdc0de5000)
libruntime,sync-atomic.so => /usr/local/go/pkg/linux_amd64_dynlink/libruntime,sync-atomic.so (0x00007fda01715000)
libdummy.so => /home/nadeem/go/pkg/linux_amd64_dynlink/libdummy.so (0x00007fda01281000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fda00eb7000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fda00c99000)
/lib64/ld-linux-x86-64.so.2 (0x00007fda01b12000)
nadeem@myznc:~/go/src$ ./main
Hello World
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment