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

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python