Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C library in Golang(v1.3.2)

Tags:

c

go

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 ?

like image 673
WoooHaaaa Avatar asked Feb 10 '23 09:02

WoooHaaaa


1 Answers

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"
    
like image 93
James Henstridge Avatar answered Feb 11 '23 21:02

James Henstridge