dpmrakfbx820320638 2015-08-07 01:47
浏览 44

如何在Golang中使用C库(v1.3.2)

This is my Go source :

package facerec

/*
#include "libs/facerec_lib.h"
*/
import "C"

// import "unsafe"

type FaceRecServiceImpl struct {
}

func (this *FaceRecServiceImpl) Compare(features1 []byte, features2 []byte) (r float64, err error) {
    // TODO
    result := C.sumUp(2, 3)
    return float64(result), nil
}

facerec_lib.h

int sumUp(int a, int b);

facerec_lib.c

/* File facerec.c */
#include "facerec_lib.h"

int sumUp(int a, int b)
{
  return a + b;
}

go build:

Roy-MacBook-Air:facerec $ go build
# xxx/facerec
Undefined symbols for architecture x86_64:
  "_sumUp", referenced from:
      __cgo_35aa8b5c98e0_Cfunc_sumUp in face_rec.cgo2.o
     (maybe you meant: __cgo_35aa8b5c98e0_Cfunc_sumUp)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Roy-MacBook-Air:facerec$

How can I deal with this issue ? Thanks a lot !

EDIT

I changed facerec_lib.h to facerec_lib.c, problem solved, I thinks I must miss some FLAGS in go file, any hints ?

  • 写回答

1条回答 默认 最新

  • dougekui1518 2015-08-07 15:13
    关注

    If you make use of a C function via cgo, you must make sure that the implementation of that function is linked into your Go package. From the comments on your question, it seems this was not the case.

    Two ways you can go about this include:

    1. place a .c file in your package's directory that implements the function. When you run go build, it will be compiled and linked into your package along with the Go code.

    2. If the function is implemented in a library, you can use the LDFLAGS directive in the comment before an import "C" statement in a Go file. For example:

      // #cgo LDFLAGS: -lmylib
      import "C"
      
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本