如何在Go中引入第三方包的头文件?

huangapple go评论79阅读模式
英文:

How to include headers from a third party package in Go?

问题

假设我的包工作区中有一个名为github.com/yada/yada的第三方包。在这个包中,有一个名为yoda.go.h的头文件,我想要重用它(不确定这是否是一个好主意,但这是一个全新的问题)。我该如何将依赖包中的头文件导入到我的包中?

package main

// #cgo pkg-config: my-dep other-dep
// #include <someHeader.h>
// #include <otherHeader.h>
// #include github.com/yada/yada/yoda.go.h // 不起作用 :(
import "C"

除了是否是一个好主意,我仍然想知道是否可能实现。

PS:如果你认为这真的是一个坏主意,那我应该做些什么呢?

英文:

Let's supose my package workspace has github.com/yada/yada third party package. Inside this package there is a yoda.go.h header I would like to reuse (not sure if it's a good idea, but that's a hole new question). How do I import the header from a dependecy package into my own package?

package main

// #cgo pkg-config: my-dep other-dep
// #include &lt;someHeader.h&gt;
// #include &lt;otherHeader.h&gt;
// #include github.com/yada/yada/yoda.go.h // doesn&#39;t work :(
import &quot;C&quot;

Apart from being a good idea or not, I still would like to know if it's possible.

PS: If you think it's really a bad idea, what should I do instead?

答案1

得分: 3

使用CGO CFLAGS指令引用额外的包含路径。

//#cgo CFLAGS: -I $GOPATH/src/github.com/yada/yada/
...
//#include "yoda.go.h"
import "C"

更正

在构建过程中,go工具不会展开$GOPATH变量。相反,应该在那里使用完整路径。更正后的代码如下:

//#cgo CFLAGS: -I /full/path/to/src/github.com/yada/yada/
//#include "yoda.go.h"
英文:

Use CGO CFLAGS directive to reference additional include path.

//#cgo CFLAGS: -I $GOPATH/src/github.com/yada/yada/
...
//#include &quot;yoda.go.h&quot;
import &quot;C&quot;

CORRECTION:

The go tool does not expand $GOPATH variable during build. Instead, the full path should be used there. Corrected code:

//#cgo CFLAGS: -I /full/path/to/src/github.com/yada/yada/
//#include &quot;yoda.go.h&quot;

答案2

得分: 1

可能不是一个好主意直接引用它,因为它不是一个导出的实体,而且可能会发生变化或被删除。

如果你真的需要那个头文件,你将不得不直接在你的本地文件系统中引用它。(当然,你也可以将其复制到你的项目中)

英文:

Probably not a good idea to try and reference it directly, since it's not an exported entity, and is subject to change or removal.

If you really need that header, you'll have to reference it directly in your local filesystem. (of course you're free to copy into your project too)

huangapple
  • 本文由 发表于 2014年12月5日 21:41:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/27317210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定