Home > Net >  Can Go executable be used as a dynamic library?
Can Go executable be used as a dynamic library?

Time:01-07

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?

CodePudding user response:

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
$

CodePudding user response:

I believe it is possible using cgo: https://pkg.go.dev/cmd/cgo

It is stated that Go functions can be exported for use by C code.

  • Related