dongpu8935 2017-04-30 20:25
浏览 91
已采纳

交叉编译共享库

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条回答 默认 最新

  • dqwd71332 2017-05-03 17:07
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog