Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: How to link C objects using CGO_OFILES?

Tags:

makefile

go

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?

like image 716
Alasdair Avatar asked Oct 17 '14 06:10

Alasdair


1 Answers

  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"
like image 165
user918176 Avatar answered Nov 15 '22 04:11

user918176