6

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?

8
  • 1
    What leads you to beliueve that there is a CGO_OFILES variable? Commented Oct 17, 2014 at 6:23
  • It's mentioned in a few different places. If you search for it you'll see. It's not documented though. Commented Oct 17, 2014 at 6:25
  • I guess it's gone away. Grepping through the source of cgo, I couln't find any reference to that. Commented Oct 17, 2014 at 6:25
  • You mean to say it used to exist but does not exist in the current version? If so it surely must have been replaced with something else? Commented Oct 17, 2014 at 6:27
  • I don't know. Is the object file you want to link generate from C source code in your case or do you want to ship literally an object file? Commented Oct 17, 2014 at 7:53

2 Answers 2

4
  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"
Sign up to request clarification or add additional context in comments.

Comments

0

Use .syso istead of .o extension.

go build now automatically links every .syso files found in derectory into your binary.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.