Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Go executable be used as a dynamic library?

I am writing a generic library in GoLang and want to publish it (like a dynamic library) to be used by other apps written in any language.

If I write this lib in C/C++, I would have generated a .dll or .so file which can be imported and used in any other language. How can I do this in GoLang?

If I just generate a Go executable, can I use it instead of a dynamic library?

like image 204
RGC Avatar asked Oct 15 '25 04:10

RGC


1 Answers

You can build a C-shared library in Go, this will produce a regular .dll or .so with exported functions compatible with the C calling convention, so that they can be invoked from other languages.

Compile with go build -buildmode=c-shared.

See go build command - Build modes

For example:

src/go/main.go:

package main

import "C"
import "fmt"

//export helloLib
func helloLib(x C.int) {
    fmt.Printf("Hello from Go! x=%d\n", x)
}

func main() {}

src/c/main.c:

void helloLib(int);

int main() {
    helloLib(12345);
}

Building and running:

$ go build -buildmode=c-shared -o libmy.so ./src/go/
$ gcc -o test src/c/main.c libmy.so
$ ./test
Hello from Go! x=12345
$
like image 189
rustyx Avatar answered Oct 17 '25 23:10

rustyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!