duanfei7508 2014-11-29 05:40
浏览 65

与C库进行包链接

I hope this is a basic question. I am trying to build a Go package which includes functions from a library written in C. The structure is basically as follows:

package too

/*
#cgo LDFLAGS: -L/usr/local/lib include -lbar
#include mybar.h
*/
import "C"

func MyGoWrapper () {
  C.orig_func()
}

Running go build foo.go fails with an "undefined reference" for orig_func. Note that the header is mybar.h; I created a prototype for orig_func that was not included in the original library. Do I need to recompile the library first, including this header file, before it will link with the Go build? Or am I misunderstanding something else entirely?

  • 写回答

1条回答 默认 最新

  • dongzj2015 2014-11-29 07:20
    关注

    When linking against an external library, you do need to separately compile it for your target architecture. cgo can't replace the configure/make (or whatever) to compile the library; it only knows how to build a few .c files in your package directory, and a library's build process might be more complex.


    I'm less sure of how to accomplish the larger task of linking in an external library when cross-compiling (and I'm not sure what you've already done). The (closed) Go bug on cross-compilation with cgo looks useful here. You may want to build the Go toolchain with some environment variables set that are described in godoc cmd/cgo:

    To enable cgo during cross compiling builds, set the CGO_ENABLED environment variable to 1 when building the Go tools with make.bash. Also, set CC_FOR_TARGET to the C cross compiler for the target. CC will be used for compiling for the host.

    After the Go tools are built, when running the go command, CC_FOR_TARGET is ignored. The value of CC_FOR_TARGET when running make.bash is the default compiler. However, you can set the environment variable CC, not CC_FOR_TARGET, to control the compiler when running the go tool.

    CXX_FOR_TARGET works in a similar way for C++ code.

    The bug also mentions someone who uses -ldflags="-extld=$(CC)" (where $(CC) is the name of the cross-compiler they want to use).

    In your example code there's an explicit -L/usr/local/lib and I don't think that'll work: I think when you build libraries for the target, you're going to want to put them in a directory distinct from the lib for your host arch. For example, this ARM cross-compilation HOWTO uses a /usr/local/arm-linux prefix or install_root in some places.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。