英文:
Golang: How to link C objects using CGO_OFILES?
问题
我正在为你翻译以下内容:
我因为这个问题而焦头烂额。
我只想做的是将一个.o(C对象文件)与一个Go包链接起来,这样Go包就可以调用C函数。
在cgo的CGO_OFILES
参数上似乎没有任何文档,经过我在互联网上的大量搜索后,这似乎是我需要的。
我尝试将以下内容放在Go文件的顶部:
/*
#cgo CGO_OFILES: doc-capi-tesseract.o
#include <stdlib.h>
#include "doc-capi-tesseract.h"
*/
import "C"
但是这给我报错了,错误信息是invalid #cgo verb: #cgo CGO_OFILES: doc-capi-tesseract.o
。然后我在某个地方读到可以使用一个makefile,所以我创建了这个可能不正确的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 $^
但是我不知道该如何处理这个文件。如果我运行make
或make myfile
或go build makefile
,什么都不会发生。不知道该如何使用它。
请问有人可以向我解释如何将一个Go文件链接到一个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?
答案1
得分: 4
你可以使用SWIG,因为它提供了更多的灵活性。我刚刚学会了如何在C++中使用它(示例),但是与C语言的过程几乎相似。你可以选择静态链接和动态链接,两种方法都可以工作。
你可以通过定义正确的标志来强制CGO进行静态链接(示例,特别是提到的GitHub存储库!)。
示例 #2:
// #cgo CFLAGS: -Isrc/include
// 这里是doc-capi-tesseract.h的路径!
// #cgo LDFLAGS: doc-capi-tesseract.a
// #include "doc-capi-tesseract.h"
import "C"
英文:
- 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.
- 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"
答案2
得分: 0
使用 .syso 扩展名代替 .o 扩展名。
现在,go build 命令会自动将目录中找到的每个 .syso 文件链接到您的二进制文件中。
英文:
Use .syso istead of .o extension.
go build now automatically links every .syso files found in derectory into your binary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论