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"
    
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程