交叉编译共享库

huangapple go评论104阅读模式
英文:

Cross compile shared libraries

问题

我想知道是否有可能(如果是的话:如何)使用Go交叉编译共享库。假设我有以下代码:

package main

import "C"

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

func main() {}

src/doubler/main.go中。在Mac上,我可以运行以下命令:

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

以生成名为libdoubler.dylib的共享库。在Linux上类似,只是扩展名为.so

现在,我想使用Linux作为主要平台来构建我的库(用于Mac和Windows)。我有哪些选择?

GOOS设置为darwin并在Linux上运行上述命令,我得到以下错误信息:

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

有什么想法吗?

英文:

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?

答案1

得分: 7

你面临的问题实际上不是关于编译共享库或可执行文件,而是关于使用cgo并尝试交叉编译的问题。(不过,如果你想要一个库而不是可执行文件,包名不应该是main。)

在交叉编译时,默认情况下会禁用cgo。如果你添加环境变量CGO_ENABLED=1,那么你的示例将可以工作:

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

请记住,在交叉编译时使用cgo会很麻烦。你需要确保目标平台的C库已经准备好在你的主机上。如果没有真正必要,尽量避免使用cgo。如果必须使用,你可以考虑在目标机器上进行编译,而不是处理使用cgo进行交叉编译的维护工作。

英文:

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.

答案2

得分: 0

当构建一个客户端时,请使用:

package main

...然而,当构建一个库时,请使用:

package mylibname
英文:

when building a client use :

package main 

... however building a library use :

package mylibname

huangapple
  • 本文由 发表于 2017年5月1日 04:25:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/43710987.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定