交叉编译共享库 [英] Cross compile shared libraries

查看:101
本文介绍了交叉编译共享库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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() {}

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

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

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

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

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

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

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

GOOS 设置为 darwin 并在上面运行linux,我得到

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

有什么想法吗?

推荐答案

您面临的问题实际上与编译共享库或可执行文件有关,而与使用cgo并尝试交叉编译有关。 (不过,如果您要的是库而不是可执行文件,则程序包名称不应为 main 。)

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.)

交叉编译时,默认情况下cgo是禁用的。如果添加环境变量 CGO_ENABLED = 1 ,那么您的示例将起作用:

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



<请记住,在交叉编译时使用cgo会很麻烦。您将需要确保目标平台上的C库已在主机上准备好。如果没有必要,请远离cgo。如果需要的话,您可以考虑在目标计算机上进行编译,而不是使用cgo处理交叉编译。

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.

这篇关于交叉编译共享库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆