douzi4766 2014-10-17 06:13
浏览 123

Golang:如何使用CGO_OFILES链接C对象?

I'm pulling my hair out because of this.

All I want to do is link a .o (C object file) with a Go package so the Go package can call the C functions.

There does not appear to be any documentation on CGO_OFILES parameter of cgo, which appears to be what I need after much Internet searching.

I've tried putting this at the top of the Go file:

/*
#cgo CGO_OFILES: doc-capi-tesseract.o
#include <stdlib.h>
#include "doc-capi-tesseract.h"
*/
import "C"

But that gives me the error invalid #cgo verb: #cgo CGO_OFILES: doc-capi-tesseract.o. Then I read somewhere that a makefile can be used, so I made this probably incorrect makefile:

include $(GOROOT)/src/Make.inc
TARG=tesseract
CGOFILES=tesseract.go
CGO_OFILES=doc-capi-tesseract.o
include $(GOROOT)/src/Make.pkg

%.o: %.cpp
    $(HOST_CC) $(CGO_CFLAGS_$(GOARCH)) -g -O2 -fPIC -o $@ -c $^

But I have no idea then what to do with that file. Nothing happens if I run make or make myfile or go build makefile. No idea how to use it.

Could someone please explain to me how to link a Go file to a C object file?

  • 写回答

2条回答

  • dongqiang5541 2014-12-03 19:28
    关注
    1. You could use SWIG because it gives you more versatility. I just learnt myself to use it with C++ (example) but the process is 99% similar with C. You can choose between static and dynamic linking, both approaches will work.
    2. You can force CGO to link statically (example, see especially the mentioned github repo!) by defining correct flags.

    Example to #2:

    // #cgo CFLAGS: -Isrc/include  
    // Where doc-capi-tesseract.h is!
    // #cgo LDFLAGS: doc-capi-tesseract.a
    // #include "doc-capi-tesseract.h"
    
    import "C"
    
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图