5

I'd like to know if it is possible (and if yes: how) to cross compile shared libraries with Go. Say I have this code:

package main

import "C"

//export DoubleIt
func DoubleIt(x int) int {
    return x * 2
}

func main() {}

in src/doubler/main.go. On Mac I can run

go build -o libdoubler.dylib -buildmode=c-shared doubler

to get a shared library called libdoubler.dylib. Similar on linux, just with the extension .so.

Now I'd like to use Linux as the main platform to build my libraries (for Mac and Windows). What are my options?

Setting GOOS to darwin and running the above on linux, I get

can't load package: package doubler: no buildable Go source files in /home/patrick/Desktop/go/src/doubler

Any ideas?

2 Answers 2

8
+200

The problem you face is not actually about compiling shared libraries or executables, but about using cgo and trying to cross-compile. (Still, if you want a library, not an executable, package name shouldn't be main.)

When cross-compiling, cgo is disabled by default. If you add the environment variable CGO_ENABLED=1, then your example will work:

CGO_ENABLED=1 GOOS=darwin go build -o libdoubler.dylib -buildmode=c-shared doubler

Keep in mind that using cgo while cross-compiling will be cumbersome. You will need to make sure that C libraries for the target platform are ready on your host machine. If it is not really necessary, stay away from cgo. If you have to, then you may consider compiling on the target machine instead of dealing with the maintenance of cross-compiling with cgo.

6
  • To say, don't works on my machine. ld unrecognizes flags and gcc returns exit status 1 May 3, 2017 at 17:31
  • package main and -buildmode=c-shared won't work together. I assumed the OP was aware of it as another answer already stated that problem. I have edited my answer to clarify this point. Thank you very much!
    – hasanyasin
    May 3, 2017 at 17:42
  • I have always misspelled CGO_ENABLED... Now it "works" in a sense that it doesn't throw any errors anymore. I whish the solution would have been without installing a cross compilation environment.
    – topskip
    May 3, 2017 at 18:38
  • @hasanyasin I have no problems with package main on OS X.
    – topskip
    May 3, 2017 at 18:41
  • If package is main, we are cross-compiling with GOOS=darwin on a linux machine and we want it to produce a shared package, then linking fails as uvelichitel mentioned. If you use pure go, then cross-compiling is a breeze. If you use non-Go libraries, then there is no way around having those libraries for the target platform. Can't play lego without lego bricks. :)
    – hasanyasin
    May 3, 2017 at 18:51
0

when building a client use :

package main 

... however building a library use :

package mylibname
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.