英文:
How to use C library in Golang(v1.3.2)
问题
这是我的Go源代码:
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$
我该如何处理这个问题?非常感谢!
编辑
我将facerec_lib.h
更改为facerec_lib.c
,问题解决了。我想我可能在Go文件中漏掉了一些FLAGS
,有什么提示吗?
英文:
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
得分: 9
如果你通过cgo使用一个C函数,你必须确保该函数的实现已经链接到你的Go包中。根据你问题的评论,似乎并非如此。
有两种方法可以解决这个问题:
-
在你的包目录中放置一个
.c
文件来实现该函数。当你运行go build
时,它将与Go代码一起编译和链接到你的包中。 -
如果该函数是在一个库中实现的,你可以在Go文件中的
import "C"
语句之前的注释中使用LDFLAGS指令。例如:// #cgo LDFLAGS: -lmylib import "C"
英文:
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:
-
place a
.c
file in your package's directory that implements the function. When you rungo build
, it will be compiled and linked into your package along with the Go code. -
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论